【问题标题】:How can I convert base64 string to image and upload the file in storage and save the path in the database如何将base64字符串转换为图像并将文件上传到存储中并将路径保存在数据库中
【发布时间】:2019-11-29 08:46:02
【问题描述】:

我正在构建一个 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);从数据库表中获取团队时。但现在我没有得到正确的路径,任何帮助将不胜感激

【问题讨论】:

    标签: php laravel vuejs2 laravel-5.8


    【解决方案1】:

    这种方式可以从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)
    

    【讨论】:

    • 这似乎工作正常。但我也想将该网址存储在表格中!我该怎么做?
    • 存储文件的唯一名称。像 $team->image = $filename;并将其保存到数据库中。如果您想在 Vue 或刀片部分中显示此文件,请在 img 标签 (127.0.0.1:8000/storage/folderName/{{$team->image}}) 中使用此 URL,并请检查 VueJs 的语法
    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    相关资源
    最近更新 更多