ajax函数的返回类型只有xml、text、json、html等类型,请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,ajax没法解析后台返回的文件流。所以直接用ajax直接调用接口下载得到的是一串乱码,如图:

需要对返回的数据做些处理才能得到正确的文件:

$.ajax({
    url: myUrl,
    type: 'POST',
    data: myData,
    success: function(res, status, xhr) {
     const fileName = `${res.title}.xlsx`
      if (window.navigator.msSaveOrOpenBlob) {
         window.navigator.msSaveBlob(res, fileName)
       } else {
         const downloadLink = window.document.createElement('a')
         downloadLink.href = window.URL.createObjectURL(new Blob([res]), { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
         downloadLink.download = fileName
         document.body.appendChild(downloadLink)
         downloadLink.click()
         document.body.removeChild(downloadLink)
       }
    }
   })

使用 { type: ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’ }的写法,把表格格式保存为 xlsx 。
临时创建a标签并为它创建临时地址URL.createObjectURL(blob),点击之后文档就下载成功啦,最后再把a标签移除。

blob导出文件对应的type:

后缀type
docapplication/msword
docxapplication/vnd.openxmlformats-officedocument.wordprocessingml.document
xlsapplication/vnd.ms-excel
xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
pptapplication/vnd.ms-powerpoint
pptxapplication/vnd.openxmlformats-officedocument.presentationml.presentation

更多推荐

利用ajax从服务端获取excel文件