Search code examples
laravelbase64

Laravel base64 file move into one folder


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?


Solution

  • 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.";
    }