downLoadFile.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import axios from 'axios'
  2. import qs from 'qs'
  3. import {
  4. getToken
  5. } from '@/utils/auth'
  6. import load from '@/utils/loading'
  7. /**
  8. * 导出模板
  9. * @param {*} params
  10. * params: {
  11. * url: xxx,
  12. * params: {},
  13. * fileName: xxx.xls
  14. * }
  15. */
  16. export const Export = (that, params, message) => {
  17. // 报表导出
  18. let url = params.url
  19. const options = {
  20. method: params.method ? params.method : 'get',
  21. headers: {
  22. Authorization: getToken()
  23. },
  24. // params: params.params,
  25. url,
  26. responseType: "blob"
  27. };
  28. if(options.method == 'post') {
  29. options.data =params.params
  30. } else {
  31. options.params = params.params
  32. }
  33. that.$confirm((message || "您确定下载模板"), "提示", {
  34. confirmButtonText: "确定",
  35. cancelButtonText: "取消",
  36. type: "warning"
  37. })
  38. .then(() => {
  39. load.startLoading()
  40. axios(options).then(res => {
  41. let blob = new Blob([res.data], {
  42. // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  43. type: "application/vnd.ms-excel;charset=utf-8"
  44. //word文档为application/msword,pdf文档为application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
  45. });
  46. let text = (new Response(blob)).text()
  47. text.then(res => {
  48. // 判断是否报错
  49. if (res.indexOf('code') != -1) {
  50. let json = JSON.parse(res)
  51. that.$message.error(json.msg)
  52. } else {
  53. let objectUrl = URL.createObjectURL(blob);
  54. let link = document.createElement("a");
  55. let fname = params.fileName || "导出文件.xls"; //下载文件的名字
  56. link.href = objectUrl;
  57. link.setAttribute("download", fname);
  58. document.body.appendChild(link);
  59. link.click();
  60. }
  61. })
  62. load.endLoading();
  63. }).catch(error => {
  64. that.$message.error('下载失败,请联系管理员');
  65. load.endLoading();
  66. });
  67. })
  68. .catch(() => {});
  69. }