excel - 如何使用 laravel 和 vuejs 下载文件

标签 excel vue.js laravel-5.8

我在 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 并下载它已损坏
附加信息
当我使用 writer save 时也试过这句话
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 部分的一些东西,但不确定

最佳答案

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

更改存储文件的方法,而不是发送和返回名称

创建其他方法或新 Controller 来下载文件

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")
})

关于excel - 如何使用 laravel 和 vuejs 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60455312/

相关文章:

php - Laravel:如何使用 Eloquent 获取关系列的 SUM

php - Laravel 上的图像更新并删除旧图像

excel - 使用 ws.QueryTables.Add 导入 CSV 时出现问题

arrays - 使用 ARRAY 中的变量声明 Cells(row,col)

python - Openpyxl 不会以只读模式关闭 Excel 工作簿

javascript - 如何在 Vue-CLI 3 项目中全局声明 jQuery?

当在同一行的另一个单元格中输入数据时,Excel 公式将日期/时间放入单元格中

javascript - 在循环外使用 v-for 键

vue.js - Nuxt + Axios 作为插件请求失败 404

php - 如何在 Laravel 或 Php 中手动增加获取的数据值?