download.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { saveAs } from 'file-saver'
  2. import axios from 'axios'
  3. import { getToken } from '@/utils/auth'
  4. import { Message } from 'element-ui'
  5. const baseURL = process.env.VUE_APP_BASE_API
  6. export default {
  7. name(name, isDelete = true) {
  8. var url = baseURL + "/common/download?fileName=" + encodeURI(name) + "&delete=" + isDelete
  9. axios({
  10. method: 'get',
  11. url: url,
  12. responseType: 'blob',
  13. headers: { 'Authorization': 'Bearer ' + getToken() }
  14. }).then(async (res) => {
  15. const isLogin = await this.blobValidate(res.data);
  16. if (isLogin) {
  17. const blob = new Blob([res.data])
  18. this.saveAs(blob, decodeURI(res.headers['download-filename']))
  19. } else {
  20. Message.error('无效的会话,或者会话已过期,请重新登录。');
  21. }
  22. })
  23. },
  24. resource(resource) {
  25. var url = baseURL + "/common/download/resource?resource=" + encodeURI(resource);
  26. axios({
  27. method: 'get',
  28. url: url,
  29. responseType: 'blob',
  30. headers: { 'Authorization': 'Bearer ' + getToken() }
  31. }).then(async (res) => {
  32. const isLogin = await this.blobValidate(res.data);
  33. if (isLogin) {
  34. const blob = new Blob([res.data])
  35. this.saveAs(blob, decodeURI(res.headers['download-filename']))
  36. } else {
  37. Message.error('无效的会话,或者会话已过期,请重新登录。');
  38. }
  39. })
  40. },
  41. zip(url, name) {
  42. var url = baseURL + url
  43. axios({
  44. method: 'get',
  45. url: url,
  46. responseType: 'blob',
  47. headers: { 'Authorization': 'Bearer ' + getToken() }
  48. }).then(async (res) => {
  49. const isLogin = await this.blobValidate(res.data);
  50. if (isLogin) {
  51. const blob = new Blob([res.data], { type: 'application/zip' })
  52. this.saveAs(blob, name)
  53. } else {
  54. Message.error('无效的会话,或者会话已过期,请重新登录。');
  55. }
  56. })
  57. },
  58. saveAs(text, name, opts) {
  59. saveAs(text, name, opts);
  60. },
  61. async blobValidate(data) {
  62. try {
  63. const text = await data.text();
  64. JSON.parse(text);
  65. return false;
  66. } catch (error) {
  67. return true;
  68. }
  69. },
  70. }