download-file.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { RequestFile } from './request-file'
  2. import { downloadByStream, getFileNameFormHeader } from './util'
  3. export class DownloadFile extends RequestFile {
  4. constructor ({ type, method = 'get', apiName, url, params = {}, data, config = {}, pathParams = {}, headers = {} }) {
  5. method = type || method
  6. super({ method, apiName, url, data, pathParams, params, config, headers })
  7. this.config.responseType = 'blob'
  8. this.cancelMessage = '已取消下载'
  9. }
  10. async send () {
  11. try {
  12. const res = await this.request()
  13. const filenameISO = getFileNameFormHeader(res.headers['content-disposition'])
  14. const filename = this.config.encodeType === 'iso' ? decodeURI(escape(filenameISO)) : filenameISO//
  15. downloadByStream(res.data, filename)
  16. } catch (err) {
  17. this.notifyError(err)
  18. throw err
  19. }
  20. }
  21. }
  22. // export class DownloadFile {
  23. // constructor ({ type = 'get', apiName, url, params = {}, data, config = {}, pathParams = {}, headers = {} }) {
  24. // this.type = type.toLocaleLowerCase()
  25. // this.path = getRequestPath(apiName, url, pathParams)
  26. // config.timeout = 0
  27. // config.params = params
  28. // this.cancel = () => {} // noop
  29. // this.abort = this.abort.bind(this) // 显示的绑定
  30. // const _this = this
  31. // config.cancelToken = new CancelToken(function (c) {
  32. // _this.cancel = c
  33. // })
  34. // // download特有
  35. // this.data = data
  36. // config.headers = Object.assign({}, { 'Content-Type': 'application/octet-stream;charset=UTF-8' }, config.headers, headers)
  37. // config.responseType = 'blob'
  38. //
  39. // this.config = config
  40. // }
  41. //
  42. // send () {
  43. // return new Promise((resolve, reject) => {
  44. // // put,post第二个参数为data
  45. // const params2 = ['put', 'post'].includes(this.type) ? this.data : this.config
  46. // axios[this.type](this.path, params2, this.config).then(res => {
  47. // const filenameISO = getFileNameFormHeader(res.headers['content-disposition'])
  48. // const filename = this.config.encodeType === 'iso' ? decodeURI(escape(filenameISO)) : filenameISO//
  49. // downloadByStream(res.data, filename)
  50. // resolve()
  51. // }).catch(async err => {
  52. // const message = await notifyErrorMessage(err)
  53. // CipMessage({ type: 'error', message })
  54. // reject(err)
  55. // })
  56. // })
  57. // }
  58. //
  59. // abort () {
  60. // this.cancel('已取消下载')
  61. // }
  62. // }