1. post 请求

  1. export default function (data) {
  2. axios({
  3. method: 'post',
  4. url: data.url, //后端接口地址
  5. responseType: 'blob', //bolb格式的请求方式
  6. headers: {
  7. Authentication: getToken('Admin-Token') //请求头
  8. },
  9. data: data.data //需要传给后端的请求参数体
  10. }).then(res => {
  11. const BLOB = res.data;
  12. const fileReader = new FileReader();
  13. fileReader.readAsDataURL(BLOB); //对请求返回的文件进行处理
  14. fileReader.onload = (e) => {
  15. let a = document.createElement('a');
  16. a.download = data.name + '.xlsx'
  17. a.href = e.target.result;
  18. document.body.appendChild(a)
  19. a.click();
  20. document.body.removeChild(a)
  21. }
  22. }).catch(err => {
  23. console.log(err.message)
  24. })
  25. }

fileReader详解

2. get 请求

  1. export default function (data) {
  2. axios({
  3. url: data.url,
  4. method: 'get',
  5. responseType: 'blob',
  6. params: data.data, //与post传参方式不同之处
  7. headers: {
  8. Authentication: getToken()
  9. }
  10. }).then(res => {
  11. var blob = new Blob([res.data],
  12. {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});
  13. var filename = data.name + '.xlsx';
  14. var downloadElement = document.createElement('a');
  15. var href = window.URL.createObjectURL(blob); //创建下载的链接
  16. downloadElement.style.display = 'none';
  17. downloadElement.href = href;
  18. downloadElement.download =filename ; //下载后文件名
  19. document.body.appendChild(downloadElement);
  20. downloadElement.click(); //点击下载
  21. document.body.removeChild(downloadElement); //下载完成移除元素
  22. window.URL.revokeObjectURL(href); //释放掉blob对象
  23. }
  24. }

比较实用的写法 (导出xls)

  1. async outImport () {
  2. await this.$axios({
  3. method: 'get',
  4. url: 'logistics-order/excel',
  5. params: this.params,
  6. responseType: 'blob'
  7. }).then((res) => {
  8. // const binaryData = []
  9. // binaryData.push(res.data)
  10. // this.url = window.URL.createObjectURL(
  11. // new Blob(binaryData, { type: 'application/vnd.ms-excel' })
  12. // )
  13. // window.open(this.url)
  14. console.log(res)
  15. let str = res.headers['content-disposition']
  16. str = str.substr(str.indexOf('=') + 1, str.length)
  17. console.log(str.split('.'))
  18. this.downloadFile(res.data, decodeURI(str.split('.')[0] + '.xls'))
  19. })
  20. },
  21. downloadFile (blob, fileName) {
  22. if (window.navigator.msSaveOrOpenBlob) {
  23. navigator.msSaveBlob(blob, fileName)
  24. } else {
  25. const link = document.createElement('a')
  26. const evt = document.createEvent('HTMLEvents')
  27. evt.initEvent('click', false, false)
  28. link.href = URL.createObjectURL(blob)
  29. link.download = fileName
  30. link.style.display = 'none'
  31. document.body.appendChild(link)
  32. link.click()
  33. window.URL.revokeObjectURL(link.href)
  34. }
  35. }