簡體   English   中英

使用 vue.js 從 laravel 不支持下載的文件

[英]Downloaded File not supported from laravel using vue.js

我的函數可以使用 laravel 和 vue.js 下載我想要的確切文件,但是當我嘗試打開下載的文件時,它顯示unsupported file type

我的 vue.js 函數來獲取文件信息:

downloadFile(file){
  this.$axios.post(`file/download`, file).then(({data}) => {
    this.download(data, file)
  })
},

我的 Laravel 控制器:

$file = public_path() . "/images/" . $request['file_name'];
$headers = ['Content-Type' => 'application/jpeg'];
return response()->download($file, $request['file_name'], $headers);

最后,我的 vue.js 函數用於下載創建 URL 鏈接的圖像:

download(data, file) {
    const url = window.URL.createObjectURL(new Blob([data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', file.file_name);
    document.body.appendChild(link);

    link.click();
}

因為后端已經返回“下載”數據您不應該在前端獲取它然后在新選項卡中打開它。 您可以在新選項卡中打開它而無需獲取

downloadFile(fileName){
 this.download(fileName)
},

download(file_name) {
    const link = document.createElement('a');
    link.href = `yoururl/${file_name}`;
    link.setAttribute('download', file_name);
    document.body.appendChild(link);
    link.click();
}

同樣在后端部分,您應該使用“get”路由這樣的方法

public function download($filename) {
  $file = public_path() . "/images/" . $filename;
  $headers = ['Content-Type' => 'application/jpeg'];
  return response()->download($file, $filename, $headers);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM