upload-file.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // fileUpload.js
  2. import { v4 as uuidv4 } from 'uuid'
  3. import axios from 'axios'
  4. import { getOssConfig } from '@/api/common'
  5. import { getToken } from '@/utils/auth'
  6. /**
  7. * @description: 文件附件上传
  8. * file: 文件raw对象
  9. * successCallback: 成功的回调函数
  10. * errCallBack: 错误的回调函数
  11. * progressCallback: 上传进度的回调函数
  12. * dir: 上传阿里云目标文件夹 eg:图片image,视频video等
  13. */
  14. const upload = async function (
  15. file,
  16. successCallback = new Function(),
  17. errCallBack = new Function(),
  18. progressCallback = new Function(),
  19. dir = 'image'
  20. ) {
  21. let fileName = file.name
  22. // 拿到签名信息后,组装表单数据,作参考,具体的字段找后台要
  23. let obj = ((await getOssConfig()) || {}).data
  24. let config = {}
  25. config.host = obj['host']
  26. config.OSSAccessKeyId = obj['OSSAccessKeyId']
  27. config.policyBase64 = obj['policy']
  28. config.signature = obj['signature']
  29. config.expire = parseInt(obj['expire'])
  30. config.dir = obj['dir']
  31. let fd = new FormData(),
  32. uuid = uuidv4(),
  33. key = `${config.dir}${uuid}${fileName}`
  34. fd.append('key', key)
  35. fd.append('success_action_status', '200')
  36. fd.append('OSSAccessKeyId', config.OSSAccessKeyId)
  37. fd.append('policy', config.policyBase64)
  38. fd.append('signature', config.signature)
  39. fd.append('success_action_status', '200')
  40. fd.append('file', file)
  41. console.log(config)
  42. if (config.host.indexOf('http:') > -1) {
  43. var protocol = window.location.protocol || 'http:'
  44. var subUrl = config.host.substring(5, config.host.length)
  45. config.host = protocol + subUrl
  46. }
  47. // 数据组装完成后,发送上传请求到阿里云oss
  48. axios({
  49. url: config.host,
  50. method: 'POST',
  51. data: fd,
  52. processData: false,
  53. cache: false,
  54. contentType: false,
  55. headers: {
  56. 'x-token': getToken() // 请求头
  57. },
  58. // 这里,我们可以做上传经度
  59. onUploadProgress: function (progressEvent) {
  60. if (progressEvent.lengthComputable) {
  61. let percent = (progressEvent.loaded / progressEvent.total) * 100 || 0
  62. progressCallback({
  63. percent: percent
  64. })
  65. }
  66. }
  67. })
  68. .then(() => {
  69. // 拿到结果后,做其他操作
  70. let size =
  71. file.size > 1000000
  72. ? parseFloat(file.size / 1000000).toFixed(2) + 'M'
  73. : parseFloat(file.size / 1000).toFixed(2) + 'KB'
  74. successCallback({
  75. attachment: fileName,
  76. aliyunAddress: key,
  77. size: size,
  78. host: config.host
  79. })
  80. })
  81. .catch(err => {
  82. errCallBack(err)
  83. })
  84. }
  85. export default upload