upload.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import env from '../config/env.js'
  2. /**
  3. * 文件上传工具
  4. * 对应PC端的 upload.js
  5. */
  6. const upload = {
  7. buildUploadPath(kind = 'img') {
  8. const typeMap = {
  9. img: 'img',
  10. aud: 'aud',
  11. vid: 'vid',
  12. file: ''
  13. }
  14. const normalizedKind = String(kind || 'img').toLowerCase()
  15. const mappedType = typeMap[normalizedKind]
  16. if (mappedType === undefined) return '/service?ssServ=ulByHttp&type=img'
  17. if (!mappedType) return '/service?ssServ=ulByHttp'
  18. return `/service?ssServ=ulByHttp&type=${mappedType}`
  19. },
  20. /**
  21. * 上传文件到服务器
  22. * @param {String} filePath - 文件临时路径
  23. * @param {Object} options - 配置选项
  24. * @param {String} options.name - 文件字段名,默认 'fileEdit'
  25. * @param {Object} options.formData - 额外的表单数据,默认 { application: '' }
  26. * @param {Boolean|String} options.loading - 是否显示loading,或loading文字
  27. * @returns {Promise} 返回服务器响应数据
  28. */
  29. uploadFile(filePath, options = {}) {
  30. const {
  31. name = 'fileEdit',
  32. formData = { application: '' },
  33. loading = true,
  34. kind = 'img'
  35. } = options
  36. // 显示 loading
  37. if (loading) {
  38. const loadingTitle = typeof loading === 'string' ? loading : '上传中...'
  39. uni.showLoading({
  40. title: loadingTitle,
  41. mask: true
  42. })
  43. }
  44. // 获取设备信息
  45. const deviceInfo = uni.getStorageSync("deviceInfo") || {}
  46. const devId = deviceInfo.deviceId || ''
  47. const sbmc = deviceInfo.model || ''
  48. // 构建上传URL,支持 img/aud/vid/file(无type)
  49. const url = this.buildUploadPath(kind)
  50. const separator = url.includes('?') ? '&' : '?'
  51. const finalUrl = `${env.baseUrl}${url}${separator}devId=${devId}&sbmc=${sbmc}`
  52. return new Promise((resolve, reject) => {
  53. uni.uploadFile({
  54. url: finalUrl,
  55. filePath,
  56. name,
  57. formData,
  58. header: (() => {
  59. const headers = {}
  60. const jsessionId = uni.getStorageSync('JSESSIONID')
  61. if (jsessionId) {
  62. headers['Cookie'] = `JSESSIONID=${jsessionId}`
  63. }
  64. return headers
  65. })(),
  66. success: (res) => {
  67. if (res.statusCode === 200) {
  68. try {
  69. // 解析返回数据,对应PC端的格式:
  70. // { fileList: [{ path: "xxx.png", fileName: "xxx.png" }] }
  71. const data = JSON.parse(res.data)
  72. resolve(data)
  73. } catch (e) {
  74. // 如果解析失败,返回原始数据
  75. resolve(res.data)
  76. }
  77. } else {
  78. reject(res)
  79. }
  80. },
  81. fail: (err) => {
  82. uni.showToast({
  83. title: '上传失败',
  84. icon: 'none'
  85. })
  86. reject(err)
  87. },
  88. complete: () => {
  89. if (loading) {
  90. uni.hideLoading()
  91. }
  92. }
  93. })
  94. })
  95. },
  96. /**
  97. * 上传图片(快捷方法)
  98. * @param {String} filePath - 图片临时路径
  99. * @param {Object} options - 配置选项
  100. * @returns {Promise<String>} 返回服务器上的图片路径
  101. */
  102. async uploadImage(filePath, options = {}) {
  103. try {
  104. const result = await this.uploadFile(filePath, {
  105. ...options,
  106. loading: options.loading !== false ? '上传图片中...' : false,
  107. kind: 'img'
  108. })
  109. // 提取文件路径(对应PC端的 result.fileList[0].path)
  110. return result?.fileList?.[0]?.path || ''
  111. } catch (error) {
  112. console.error('上传图片失败:', error)
  113. throw error
  114. }
  115. },
  116. async uploadAudio(filePath, options = {}) {
  117. try {
  118. const result = await this.uploadFile(filePath, {
  119. ...options,
  120. loading: options.loading !== false ? '上传语音中...' : false,
  121. kind: 'aud'
  122. })
  123. return result?.fileList?.[0]?.path || ''
  124. } catch (error) {
  125. console.error('上传语音失败:', error)
  126. throw error
  127. }
  128. },
  129. async uploadVideo(filePath, options = {}) {
  130. try {
  131. const result = await this.uploadFile(filePath, {
  132. ...options,
  133. loading: options.loading !== false ? '上传视频中...' : false,
  134. kind: 'vid'
  135. })
  136. return result?.fileList?.[0]?.path || ''
  137. } catch (error) {
  138. console.error('上传视频失败:', error)
  139. throw error
  140. }
  141. },
  142. async uploadCommonFile(filePath, options = {}) {
  143. try {
  144. const result = await this.uploadFile(filePath, {
  145. ...options,
  146. loading: options.loading !== false ? '上传文件中...' : false,
  147. kind: 'file'
  148. })
  149. return result?.fileList?.[0]?.path || ''
  150. } catch (error) {
  151. console.error('上传文件失败:', error)
  152. throw error
  153. }
  154. },
  155. /**
  156. * 上传头像(专用方法)
  157. * @param {String} filePath - 头像临时路径
  158. * @returns {Promise<String>} 返回服务器上的头像路径
  159. */
  160. async uploadAvatar(filePath) {
  161. return this.uploadImage(filePath, {
  162. loading: '上传头像中...'
  163. })
  164. }
  165. }
  166. export default upload