Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel base64 file move into one folder

Tags:

base64

laravel

I have a $data variable with a base64: It's either an image or a file.

I want to move this file into a folder... but It's moved as empty file.


My code:

$file_name = Input::get('file_name');

$image = base64_decode($data);

file_put_contents(public_path('/user_attachments/').$file_name, $image);


Please anyone help?

like image 872
SARAN Avatar asked Nov 25 '25 10:11

SARAN


1 Answers

You cannot include the data:URI scheme (data:image/png;base64,) inside $data.

You can remove the data:URI scheme using the explode function, which will return an array with two elements, and before use base64_decode.

  • $data[0] => the data:URI scheme.
  • $data[1] => your data.

Use it as follow, using , as delimiter. Example:

list($dataUriScheme, $data) = explode(',', $data);

Or without list:

$data = explode(',', $data)[1];

And then Try the next code:

$fileName = Input::get('file_name');
$fileStream = fopen(public_path() . '/user_attachments/' . $fileName , "wb"); 

fwrite($fileStream, base64_decode($data)); 
fclose($fileStream); 

or

// The final filename.
$fileName= Input::get('file_name');

// Upload path
$uploadPath = public_path() . "/user_attachments/" . $fileName;

// Decode your image/file
$data = base64_decode($data);

// Upload the decoded file/image
if(file_put_contents($uploadPath , $data)){
    echo "Success!";
}else{
    echo "Unable to save the file.";
}
like image 151
tomloprod Avatar answered Nov 28 '25 01:11

tomloprod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!