how to download file using laravel and vuejs

i've created a file .xlsx in laravel and i send it to vuejs like this

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

when i call this method in vuejs use this code

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

file is created in server and works fine but, at the moment i send to vue and i download it its corrupted aditional info when i use writer save also tried this sentence

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;

also corrupted, i think i missed something in vue part but not sure

Upvotes: 2

Views: 3252

Answers (1)

Charles G
Charles G

Reputation: 1381

Here is a simple solution :

Change your method to store the file instead of sending and return the name

Create an other method or a new controller to download the file

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

Upvotes: 1

Related Questions