Atef95's avatar

Save file with original extension

Hey guys

I'm trying to upload an image via restful api.. the code below works only when image is " PNG " .. otherwise I couldn't access to it.. how can I upload any image no matter is the extension?

        $image = $request->input('image');  // your base64 encoded
        $image = str_replace('data:image/png;base64,', '', $image);
        $image = str_replace(' ', '+', $image);
        $imageName = str_random(10).'.'.'png';
        \File::put(public_path(). '/images/' . $imageName, base64_decode($image));

Thank you in advance !

0 likes
3 replies
Sergiu17's avatar
$ext = $image->getClientOriginalExtension(); // method returns extension.

Instead of .png, use . $ext

1 like
lavaniapankaj's avatar

Try below code:

$file_to_be_uploaded = $request->file('file_uploader_name');

/* Get filename with extension */

$filenameWithExt = $file_to_be_uploaded->getClientOriginalName();

/* add unique value if needed with the file name. */

$file_name_to_save_in_db = time().'_'.$filenameWithExt;

/* It will store files in storage/app/your_folder_name/ directory. */

$path = $file_to_be_uploaded->storeAs('/your_folder_name/', $file_name_to_save_in_db, 'local');

1 like
Atef95's avatar
Atef95
OP
Best Answer
Level 5

Thank you guys

I just added this following code and it worked properly

 /**Extract file extension */
        $img = explode(',', $image);
        $ini =substr($img[0], 11);
        $type = explode(';', $ini);
echo $type[0]
        /** $type[0] type image */

Please or to participate in this conversation.