Laravel 文件存储:如何存储(解码)base64 图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51296733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:53:29  来源:igfitidea点击:

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

phplaravelbase64laravel-filesystemlaravel-storage

提问by PeraMika

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

如何使用Laravel 的文件系统(文件存储)方法存储 base64 图像?

For example, I can decode base64 image like this:

例如,我可以像这样解码 base64 图像:

base64_decode($encoded_image);

but all of the Laravel's methods for storing files can accept either a Illuminate\Http\Fileor Illuminate\Http\UploadedFileinstance.

但是 Laravel 的所有存储文件的方法都可以接受 aIlluminate\Http\FileIlluminate\Http\UploadedFileinstance。

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

所以我想我必须将 base64 图像(或解码的 base64 图像)转换为Illuminate\Http\Fileor Illuminate\Http\UploadedFile,但是如何?

回答by DigitalDrifter

Just use putto store the encoded contents:

仅用于put存储编码内容:

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

All it's doing is wrapping file_put_contents.

它所做的只是包装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.

你猜对了,它正在包装file_get_contents.

回答by rkj

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

您可以像这样使用 laravel 文件存储上传 base64 图像

    $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

希望它会帮助你