如何使用laravel和vuejs下载文件

问题描述 投票:0回答:1

我已经在laravel中创建了一个文件.xlsx,我将其发送到vuejs,就像这样

function excel (Request $request){
  $dlink = public_path('storage/reports/comunicacion_piciz.xlsx');
  $writer = new Xlsx($spreadsheet);
  $writer->save($dlink);
  $headers = ["Content-Type" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"];
  return response()->download($dlink,'comunicacion_piciz.xlsx', $headers);
}

当我在vuejs中调用此方法时使用此代码

sendFile () {
  request.post(`api/log/excel`, {array: this.excelData, title: this.log})
  .then(res => {
    var newBlob = new Blob([res.data], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
    console.log(res.data)
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(newBlob)
      return
    }
    const data = window.URL.createObjectURL(newBlob)
    var link = document.createElement('a')
    link.href = data
    link.download = 'comunicacion_piciz.xlsx'
    link.click()
    setTimeout(function () {
      window.URL.revokeObjectURL(data)
    }, 100) 
    this.$spinner.close()
    })
    .finally(() => {
      this.$spinner.close()
    })
  }

文件是在服务器中创建的,可以正常工作,但是目前,我发送到vue并下载了已损坏的文件附加信息当我使用作家保存时也尝试过这句话

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Reporte Excel"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;

也损坏了,我想我在Vue部分错过了一些东西,但不确定

excel vue.js laravel-5.8
1个回答
0
投票

这里是一个简单的解决方案:

更改您的方法来存储文件而不是发送并返回名称

创建其他方法或新的控制器来下载文件

this.loading = true
axios.post(your_url_to_create_xlsx_and_store,data).then(resp => {
   this.loading = false;
   window.open(your_url_to_download_your_file?file="+resp.data.filename,"_blank")
})
© www.soinside.com 2019 - 2024. All rights reserved.