dongyu9667 2018-11-13 19:31
浏览 396

Laravel - 将base64字符串转换为有效图像

To give you a grasp of what I am trying to do, here is my current code

This code is run when a post request is made to specific URL

public function uploadImage(Request $request) {
    $request->file = base64_decode(explode(',', $request->file)[1]);

    $request->validate([
        'file' => 'image|required|mimes:jpg,png',
    ]);

    $image = $request->file('file');

    $complete = $image->getClientOriginalName();
    $name = pathinfo($complete, PATHINFO_FILENAME);
    $extension = $image->getClientOriginalExtension();
    $storageName = $name.'_'.time().'.'.$extension;

    Storage::disk('public')->put($storageName, File::get($image));

    return Storage::disk('public')->path($storageName);
}

On the first line I am trying to be smart and first decode the base64 to a file (if I am correct?).

Next is a validation to validate if the file parameter in the request exists, is an image, and is a .jpg or .png

(The next lines is just about saving the "image" to the filesystem)

But the validation won't pass because the file parameter is not an image. So my question is: is it possible to convert a base64 string to a valid image in Laravel? If it is, how can this be achieved?

  • 写回答

3条回答 默认 最新

  • dou4624 2018-11-13 19:56
    关注

    Laravel can't resolve your base 64 string to a file, hence the failure of the file validator. You also won't be able to access your data with ->file('file'), since again, you're not sending over a valid file upload.

    Instead, you could do your own simple string check (perhaps index of data:image or preferably something more extensive, like imagecreatefromstring) or look into writing a custom Laravel validation rule, and then save the sent string into a file with file_put_contents.

    If you're actually wanting to do a file upload and convert that to base 64 on the server side, then you'll want to use an <input type="file">. From there, you'll be able to use built-in Laravel validation and file storage functions. Refer to this extensive guide. Once you've gotten your file, you can convert it to base64 using base64_encode (see this answer for a more thorough guide).

    I realize this answer wasn't very specific, but if you clarify exactly what you're trying to do, I can give more hands-on guidance.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么