downLoadFile.js 2.7 KB

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