Melodia's avatar

Uploading an image using it's original name

I used this code to upload an image to my database table:

public function store(Request $request)
{
    $exploded = explode(',', request('photo'));
    $decoded = base64_decode($exploded[1]);
    if(str_contains($exploded[0], 'jpeg'))
        $extension = 'jpg';
    else
        $extension = 'png';   

    $fileName = str_random().'.'.$extension;
    $path = public_path().'/'.$fileName;
    file_put_contents($path, $decoded);
    $post = Post::create([
        'title' => request('title'),
        'description' => request('description'),
        'user_id' => Auth::id(),
        'category_id' => request('category_id'),
        'photo' => $fileName
    ]);

    return response()->json([
        'post' => $post,
    ], 200);
}

In my vue file I have the following:

<input type="file" @change="imageChanged" class="form-control">

imageChanged(e){
    var fileReader = new FileReader()
    fileReader.readAsDataURL(e.target.files[0])
    fileReader.onload = (e) => {
        this.post.photo = e.target.result
    }
}

For now when I save, I get the image with a random name.

How can I save it using the original name?

Hope someone can help with this.

0 likes
0 replies

Please or to participate in this conversation.