downLoadFile.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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) => {
  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. that.$message.error(json.msg)
  53. } else {
  54. let objectUrl = URL.createObjectURL(blob);
  55. let link = document.createElement("a");
  56. let fname = params.fileName || "导出文件.xls"; //下载文件的名字
  57. link.href = objectUrl;
  58. link.setAttribute("download", fname);
  59. document.body.appendChild(link);
  60. link.click();
  61. }
  62. })
  63. load.endLoading();
  64. }).catch(error => {
  65. that.$message.error('下载失败,请联系管理员');
  66. load.endLoading();
  67. });
  68. })
  69. .catch(() => {});
  70. }