Laravel File Storage: How to store (decoded) base64 image?
Asked Answered
M

3

15

How to store base64 image using the Laravel's filesytem (File Storage) methods?

For example, I can decode base64 image like this:

base64_decode($encoded_image);

but all of the Laravel's methods for storing files can accept either a Illuminate\Http\File or Illuminate\Http\UploadedFile instance.

So I guess I'd have to convert base64 image (or decoded base64 image) to Illuminate\Http\File or Illuminate\Http\UploadedFile, but how?

Marmolada answered 12/7, 2018 at 3:4 Comment(0)
C
18

Just use put to store the encoded contents:

Storage::put('file.jpg', $encoded_image);

All it's doing is wrapping file_put_contents.

Then to read it back out:

$data = base64_decode(Storage::get('file.jpg'));

Which, you guess it, is wrapping file_get_contents.

Careaga answered 12/7, 2018 at 4:5 Comment(1)
can we use base64 encoding for pdf file as well?Carvey
H
16

You can upload your base64 Image using laravel File Storage like this

    $base64_image = $request->input('base64_image'); // your base64 encoded     
    @list($type, $file_data) = explode(';', $base64_image);
    @list(, $file_data) = explode(',', $file_data); 
    $imageName = str_random(10).'.'.'png';   
    Storage::disk('local')->put($imageName, base64_decode($file_data));

Hope it will help you

Helton answered 12/7, 2018 at 4:18 Comment(1)
You can strip away disk('local') because the default value is 'local'. Storage::put($imageName, base64_decode($file_data));Interne
B
1

2023 Working Solution:

Just use that amazing Laravel Package and do your job in just three lines:

Reference: https://github.com/oldravian/multi-source-file-uploader

$file_uploader_factory = new 
\OldRavian\FileUploader\Factories\FileUploaderFactory();
$file_uploader = $file_uploader_factory->build("base64");

//first parameter should be a string (base64 encoded string)
//second parameter is optional, if you leave that parameter then default settings will be used
$data = $file_uploader->upload($encoded_image, $uploadSettings);

The above function will return an associative array like:

[
    'filename' => 'uploaded file name',
    'path' => 'path to file location relative to the disk storage',
    'url' => 'public url to access the file in browser'
]

$uploadSettings is an associative array with the following possible keys:

  • directory: the root directory containing your uploaded files
  • disk: the storage disk for file upload. Check Laravel official documentation for more details, e.g: public, s3
  • maxFileSize (in bytes): the maximum size of an uploaded file
  • allowedExtensions: array of acceptable file extensions, e.g: ['jpg', 'png', 'pdf']

In addition to base64, this package also supports file uploading by file object and URL.

Bucharest answered 5/5, 2023 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.