download.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { saveAs } from 'file-saver'
  2. import axios from 'axios'
  3. import { getToken } from '@/utils/auth'
  4. const baseURL = process.env.VUE_APP_BASE_API
  5. export default {
  6. excel(url, params) {
  7. // get请求映射params参数
  8. if (params) {
  9. let urlparams = url + '?';
  10. for (const propName of Object.keys(params)) {
  11. const value = params[propName];
  12. var part = encodeURIComponent(propName) + "=";
  13. if (value !== null && typeof(value) !== "undefined") {
  14. if (typeof value === 'object') {
  15. for (const key of Object.keys(value)) {
  16. if (value[key] !== null && typeof (value[key]) !== 'undefined') {
  17. let params = propName + '[' + key + ']';
  18. let subPart = encodeURIComponent(params) + '=';
  19. urlparams += subPart + encodeURIComponent(value[key]) + '&';
  20. }
  21. }
  22. } else {
  23. urlparams += part + encodeURIComponent(value) + "&";
  24. }
  25. }
  26. }
  27. urlparams = urlparams.slice(0, -1);
  28. url = urlparams;
  29. }
  30. url = baseURL + url
  31. axios({
  32. method: 'get',
  33. url: url,
  34. responseType: 'blob',
  35. headers: { 'Authorization': 'Bearer ' + getToken() }
  36. }).then(res => {
  37. const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  38. this.saveAs(blob, decodeURI(res.headers['download-filename']))
  39. })
  40. },
  41. oss(ossId) {
  42. var url = baseURL + '/system/oss/download/' + ossId
  43. axios({
  44. method: 'get',
  45. url: url,
  46. responseType: 'blob',
  47. headers: { 'Authorization': 'Bearer ' + getToken() }
  48. }).then(res => {
  49. const blob = new Blob([res.data], { type: 'application/octet-stream' })
  50. this.saveAs(blob, decodeURI(res.headers['download-filename']))
  51. })
  52. },
  53. zip(url, name) {
  54. var url = baseURL + url
  55. axios({
  56. method: 'get',
  57. url: url,
  58. responseType: 'blob',
  59. headers: { 'Authorization': 'Bearer ' + getToken() }
  60. }).then(res => {
  61. const blob = new Blob([res.data], { type: 'application/zip' })
  62. this.saveAs(blob, name)
  63. })
  64. },
  65. saveAs(text, name, opts) {
  66. saveAs(text, name, opts);
  67. }
  68. }