巴青农资商城

upload.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. export function uploadNativeFile(file) {
  8. return new Promise((resolve, reject) => {
  9. const formData = new FormData()
  10. formData.append('file', file)
  11. const xhr = new XMLHttpRequest()
  12. xhr.open('POST', joinApiUrl('/common/upload'))
  13. const token = getToken()
  14. if (token) {
  15. xhr.setRequestHeader('Authorization', 'Bearer ' + token)
  16. }
  17. xhr.onload = () => {
  18. try {
  19. const body = JSON.parse(xhr.responseText || '{}')
  20. if (body.code === 200 && (body.url || body.fileName)) {
  21. resolve(body.url || body.fileName)
  22. return
  23. }
  24. reject(new Error(body.msg || '上传失败'))
  25. } catch (e) {
  26. reject(e)
  27. }
  28. }
  29. xhr.onerror = () => reject(new Error('上传失败'))
  30. xhr.send(formData)
  31. })
  32. }
  33. export function uploadFile(filePath, nativeFile) {
  34. if (nativeFile && typeof File !== 'undefined' && nativeFile instanceof File) {
  35. return uploadNativeFile(nativeFile)
  36. }
  37. return new Promise((resolve, reject) => {
  38. uni.uploadFile({
  39. url: joinApiUrl('/common/upload'),
  40. filePath,
  41. name: 'file',
  42. header: {
  43. Authorization: 'Bearer ' + getToken()
  44. },
  45. success: (res) => {
  46. try {
  47. const body = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
  48. if (body.code === 200 && (body.url || body.fileName)) {
  49. resolve(body.url || body.fileName)
  50. return
  51. }
  52. reject(new Error(body.msg || '上传失败'))
  53. } catch (e) {
  54. reject(e)
  55. }
  56. },
  57. fail: (err) => reject(err)
  58. })
  59. })
  60. }