繁体   English   中英

如何将base64字符串转换为图像并将文件上传到存储中并将路径保存在数据库中

[英]How can I convert base64 string to image and upload the file in storage and save the path in the database

我正在建造一个SPA。 我从 Laravel 控制器中的 vue 组件获取 base64 字符串。 如何将 base64 字符串转换为文件。 然后将站点上传到我的 Laravel 本地存储中,然后将路径保存在数据库表中?

我几乎搜索了每个链接并尝试了太多东西。 我什至尝试过图像干预,但我唯一能够实现的是将文件上传到 Laravel 存储中,但无法在数据库表中存储正确的路径。

这是我的控制器代码

$team = new Team;
        $team->hood_id = $user->hood->id;
        $team->title = $request->title;
        $team->max_no_of_players = $request->max_no_of_players;
        $team->description = $request->description;
        $team->about_us = $request->about_us;
        $team->email = $request->email;
        $team->contact_no = $request->contact_no;
        $team->meetup_place = $request->meetup_place;
        /**
         * Image base64 converting code starts from here
         */
        $image = $request->image;
         preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
         $image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
         $image = str_replace(' ', '+', $image);
         $imageName = 'image_' . time() . '.' . $image_extension[1]; //generating unique file name;
         $team->image = Storage::disk('public')->put($imageName, base64_decode($image));

我应该可以使用 Storage::url($image); 从数据库表中获取团队时。 但现在我没有得到正确的路径,任何帮助将不胜感激

这样就可以从Base64 URL中取文件了,我用的就是这种方式。

    $pos = strpos($fileBase64Url, ';');
    $filetype = explode('/', substr($fileBase64Url, 0, $pos))[1]; //get file type

    $contents = file_get_contents($fileBase64Url); //get the content from the URL

    $unique_name = 'filename.' . $filetype; //file name 

    Storage::put('/public/folderName/' . $unique_name, $contents); //save to the directory 

    //$unique_name (Save this name to the Database)

这是这个图像文件的路径

http://127.0.0.1:8000/storage/folderName/filename.jpg (remove public form url)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM