西藏巴青项目

upload.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { joinApiUrl } from '@/config'
  2. import { getToken } from '@/utils/auth'
  3. /**
  4. * 上传图片/视频/语音到 /common/upload(与 ruoyi-ui 一致)
  5. * @returns {Promise<string>} 文件路径 url 或 fileName
  6. */
  7. /**
  8. * H5 下由 input[type=file] 得到的 File 对象上传
  9. */
  10. export function uploadNativeFile(file) {
  11. return new Promise((resolve, reject) => {
  12. const formData = new FormData()
  13. formData.append('file', file)
  14. const xhr = new XMLHttpRequest()
  15. xhr.open('POST', joinApiUrl('/common/upload'))
  16. const token = getToken()
  17. if (token) {
  18. xhr.setRequestHeader('Authorization', 'Bearer ' + token)
  19. }
  20. xhr.onload = () => {
  21. try {
  22. const body = JSON.parse(xhr.responseText || '{}')
  23. if (body.code === 200 && (body.url || body.fileName)) {
  24. resolve(body.url || body.fileName)
  25. return
  26. }
  27. reject(new Error(body.msg || '上传失败'))
  28. } catch (e) {
  29. reject(e)
  30. }
  31. }
  32. xhr.onerror = () => reject(new Error('上传失败'))
  33. xhr.send(formData)
  34. })
  35. }
  36. export function uploadFile(filePath, nativeFile) {
  37. if (nativeFile && typeof File !== 'undefined' && nativeFile instanceof File) {
  38. return uploadNativeFile(nativeFile)
  39. }
  40. return new Promise((resolve, reject) => {
  41. uni.uploadFile({
  42. url: joinApiUrl('/common/upload'),
  43. filePath,
  44. name: 'file',
  45. header: {
  46. Authorization: 'Bearer ' + getToken()
  47. },
  48. success: (res) => {
  49. try {
  50. const body = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
  51. if (body.code === 200 && (body.url || body.fileName)) {
  52. resolve(body.url || body.fileName)
  53. return
  54. }
  55. reject(new Error(body.msg || '上传失败'))
  56. } catch (e) {
  57. reject(e)
  58. }
  59. },
  60. fail: (err) => reject(err)
  61. })
  62. })
  63. }