3

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?

tomloprod
  • 7,472
  • 6
  • 48
  • 66
SARAN
  • 127
  • 1
  • 3
  • 14
  • In user_attachments folder it will create just empty image or docs.. – SARAN Nov 08 '16 at 07:26
  • My $data is base64 file. $data = data:image/png;base64,iVBORw0KGgoAAAA...........kSuQmCC – SARAN Nov 08 '16 at 12:48
  • The problem is that `data:image/png;base64`. This turns the `$data` an invalid image data. Try without the `data:URI scheme` (`data:image/png;base64,`) – tomloprod Nov 08 '16 at 15:27
  • Possible duplicate of [Convert Base64 string to an image file?](http://stackoverflow.com/questions/15153776/convert-base64-string-to-an-image-file) – tomloprod Nov 09 '16 at 13:19

2 Answers2

8

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.";
}
tomloprod
  • 7,472
  • 6
  • 48
  • 66
0

To do it the "Laravel way", you should use the built in Storage/Flysystem driver.

Create a "disk" in the config/filesystems.php disks array, something like this

'user_attachments' => [
    'driver' => 'local',
    'root' => public_path('user_attachments')
];

Then you can save the file thorugh the Storage facade like this

Storage::disk('user_attachments')->put('filename.txt', $contents);

There is other ways to achieve this aswell but this should work

Read more here https://laravel.com/docs/5.3/filesystem

oBo
  • 992
  • 2
  • 13
  • 28