【问题标题】:How to download image using vue js and laravel如何使用 vue js 和 laravel 下载图片
【发布时间】:2022-01-26 01:00:23
【问题描述】:

单击此按钮时我有一个超链接按钮,我想从数据库中获取图像并使用 laravel 和 vue js 将其下载到用户端。下面是我的脚本文件代码

 getImage: function() {
            axios.get('/getImage/' + this.form.cashout_id )
            .then(function (r) 
                {
                const url = window.URL.createObjectURL(new Blob([r.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'file.'+r.headers.ext); //or any other extension
                document.body.appendChild(link);
                link.click();

                //hide loader
                i.loader = false
            })
            .catch(function (error) {
                        alert('Error');
            });
        },

现在这是我正在获取图像的控制器代码。

public function getimage($id)
   { 
       $cashout = CashOutDetail::findorfail($id);
       $storage_date = Carbon::parse($cashout['recorded_date']);

       return response()->download(
           storage_path('app/cashoutdetails/'. $storage_date->year .'/' . $storage_date->format('M') . '/'.  $cashout->bank_receipt),
           'filename.jpg',
           ['Content-Type' => 'image/jpg']
       );
   }

问题是我的图像正在被提取并显示在控制台窗口中,但无法下载。有人可以帮忙吗?

【问题讨论】:

  • 您能否验证该链接已成功构建。 console.log(link)
  • 在没有 JS 的情况下,下载链接是否适用于您的文件? 下载
  • 如果你已经有了cashout.recorded_date,你也许可以在你的 Vue/JS 代码中确定文件的 URL。我不确定最佳实践是什么,但它会消除 HTTP 请求,并且可能更容易呈现下载按钮/链接
  • @xuma 是的。正在建立链接。但它是未定义的,正在下载的图像也作为无效文件出现。 localhost:81-46e3-ba21-1eca8430c4e9" download="file.undefined">
  • @BernardWiesner 是的,下载链接有效,但下载的文件由于扩展名而显示无效文件

标签: php laravel vue.js


【解决方案1】:

你应该试试:

axios({
    method: 'GET',
    url: '/getImage/123.jpg',
    responseType: 'blob', // <-<<<<<<<<<< 
  }).then((response) => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '123.jpg');
    document.body.appendChild(link);
    link.click();
  });

【讨论】:

  • 谢谢!!有效 。我只需要用我的 Cashout id 参数更改 123.jpg。
猜你喜欢
  • 2020-07-13
  • 2020-09-27
  • 2018-05-28
  • 2020-10-28
  • 1970-01-01
  • 2020-11-15
  • 2021-02-08
  • 2020-05-13
  • 2020-09-01
相关资源
最近更新 更多