downLoadFile.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. import cleanDeep from 'clean-deep'
  8. /**
  9. * 导出模板
  10. * @param {*} params
  11. * params: {
  12. * url: xxx,
  13. * params: {},
  14. * fileName: xxx.xls
  15. * }
  16. */
  17. export const Export = (that, params, message, func) => {
  18. // 报表导出
  19. let url = params.url
  20. const options = {
  21. method: params.method ? params.method : 'get',
  22. headers: {
  23. Authorization: getToken()
  24. },
  25. // params: params.params,
  26. url,
  27. responseType: "blob"
  28. };
  29. if (options.method == 'post') {
  30. options.data = params.params
  31. } else {
  32. options.params = params.params
  33. }
  34. that.$confirm((message || "您确定下载模板"), "提示", {
  35. confirmButtonText: "确定",
  36. cancelButtonText: "取消",
  37. type: "warning"
  38. })
  39. .then(() => {
  40. // load.startLoading()
  41. axios(cleanDeep(options)).then(res => {
  42. let blob = new Blob([res.data], {
  43. // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  44. type: "application/vnd.ms-excel;charset=utf-8"
  45. //word文档为application/msword,pdf文档为application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
  46. });
  47. let text = (new Response(blob)).text()
  48. text.then(res => {
  49. // 判断是否报错
  50. if (res.indexOf('code') != -1) {
  51. let json = JSON.parse(res)
  52. if (json.code == 403) {
  53. that.$message.error(`登录过期,请重新登录!`)
  54. setTimeout(() => {
  55. that.$store.dispatch('user/resetToken').then(() => {
  56. location.reload()
  57. })
  58. }, 1000);
  59. return
  60. } else if(json.code == 200){
  61. that.$message.success(json.msg || json.message)
  62. } else {
  63. that.$message.error(json.msg || json.message)
  64. }
  65. if (func) {
  66. func()
  67. }
  68. } else {
  69. let objectUrl = URL.createObjectURL(blob);
  70. let link = document.createElement("a");
  71. let fname = params.fileName || "导出文件.xls"; //下载文件的名字
  72. link.href = objectUrl;
  73. link.setAttribute("download", fname);
  74. document.body.appendChild(link);
  75. link.click();
  76. if (func) {
  77. func()
  78. }
  79. }
  80. })
  81. // load.endLoading();
  82. }).catch(error => {
  83. console.log(error)
  84. that.$message.error('下载失败,请联系管理员');
  85. // load.endLoading();
  86. });
  87. })
  88. .catch(() => {});
  89. }