AJAX Download with Laravel Excel

建立時間: 2017-05-29 11:04:08
更新時間: 2017-06-15 00:56:24

Backend

 Excel::create('Filename', function($excel) {
   // ...
 })->download('xls');

 

Frontend

 $.ajax({
     url: url,
     type: 'GET',
     processData: true,
     contentType: 'application/json; charset=utf-8',
     dataType: 'binary',
     xhrFields: {
         responseType: 'blob',
     },
     success: function(result, status, xhr) {
         let responseType = xhr.getResponseHeader('content-type') || 'application/octet-binary'
         let blob = new Blob([result], { type: responseType })
         let url = URL.createObjectURL(blob)
         let randomId = `download-${Math.floor(Math.random()*1000000)}`
         let link = `<a id='${randomId}' href=${url} download='${self.filename}.xlsx'>link</a>`
         $('body').append(link)
         $(`#${randomId}`)[0].click()
         $(`#${randomId}`).remove()
     },
 });