【问题标题】:Downloading storage file using vue3 and Laravel使用 vue 3 和 Laravel 下载存储文件
【发布时间】:2022-01-14 17:21:23
【问题描述】:

我的文件存储在storage folder,当我点击下载按钮到download image fileun willingly .txt file is downloading包含响应数据。

我怎样才能让这段代码从存储文件夹中下载图像。

SQL 列数据:

file.jpg in file_name column
123 in custom_code column

控制器:

public function getdata(Request $request)
    {
        $files = Files::where('custom_code','=',$request->id)->first();
      
        $image_name= Files::where('custom_code','=',$request->id)->pluck('file_name');
        
        $image = Storage::download('uploads',$image_name);
        
        return response()->json([
            'files'=> $files, 
           'image'=> $image,     
          ], 200);
          
    }

VUE:

function download(){
 axios.get("http://127.0.0.1:8000/api/get-data/"+state.input_code, {responseType: 'blob'})
                .then(response => {
                   const url = window.URL.createObjectURL(new Blob([response.data]));
                  const link = document.createElement('a');
                  link.href = url;
                  link.setAttribute('download', response.data.file_name);
                  document.body.appendChild(link);
                  link.click();
                })
                .catch(e => {
                console.log(e);
                });
            }

HTML:

<button @click="download()">Download</button>

为什么要下载包含响应数据而不是图像的文本文件。

【问题讨论】:

    标签: jquery laravel vue.js laravel-8 vuejs3


    【解决方案1】:

    您正在从服务器以 JSON 格式返回数据:

    return response()->json([
        'files'=> $files, 
        'image'=> $image,     
    ], 200);
    

    JSON is a text format。这就是您的前端接收文本的原因。

    您的前端代码创建一个指向其刚刚收到的 JSON 的本地副本的链接,然后创建一个锚标记,将锚标记指向该链接并以编程方式单击它(所有冗余步骤):

    const url = window.URL.createObjectURL(new Blob([response.data])); // Create link to local copy of JSON
    const link = document.createElement('a'); // Create anchor tag
    link.href = url; // set href of anchor tag to link created to local copy of JSON
    link.setAttribute('download', response.data.file_name); // Set redundant attribute - never used
    document.body.appendChild(link); // Append anchor tag to body
    link.click(); // Programmatically click link
    

    您应该改用return Storage::download('uploads',$image_name);

    【讨论】:

    • 我应该改变什么来只下载文件。
    • return Storage::download('uploads',$image_name);
    • 我应该如何在 vue 中声明它而不响应,您能否编辑您的答案,以便我可以标记为已解决。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 2021-02-17
    • 2021-01-21
    • 1970-01-01
    • 2021-01-10
    • 2022-01-15
    相关资源
    最近更新 更多