response to ajax with file doesn't work

2019-08-04 00:45发布

问题:

I use jquery jtable send ajax to get excel file from server but Response::download doesn't work

  $writer = (new WriterFactory())->createWriter(new  Excel5(public_path().'/file/myExport.xls'));
  $phpExcel = $writer->convert($workbook);
  $writer->write($phpExcel);

 Response::download(public_path().'\file\myExport.xls');

回答1:

Javascript cannot access file system, you cannot use ajax to download files. Try using an iframe pointing to the file to download it.

<iframe id="downloadFrame" style="display:none"/>

When you need to download, use this script:

var iframe = document.getElementById("downloadFrame");
iframe.src = "yourpathtofile";

If you use jQuery, you can try:

$("#downloadFrame").attr("src","yourpathtofile");

Another solution is using window.open

window.open("pathtoyourfle");