upload.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { BASE_URL } from '../config/api.js'
  2. export function uploadFile(filePath, folder = 'feedback') {
  3. return new Promise((resolve, reject) => {
  4. uni.uploadFile({
  5. url: `${BASE_URL}/public/attachment/upload`,
  6. filePath,
  7. name: 'file',
  8. formData: { folder },
  9. success: (res) => {
  10. try {
  11. const body = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
  12. if (body.code === 200) {
  13. resolve(body.data)
  14. return
  15. }
  16. uni.showToast({ title: body.message || '上传失败', icon: 'none' })
  17. reject(body)
  18. } catch (e) {
  19. reject(e)
  20. }
  21. },
  22. fail: reject
  23. })
  24. })
  25. }
  26. export function chooseAndUploadImages(count = 3, folder = 'feedback') {
  27. return new Promise((resolve, reject) => {
  28. uni.chooseImage({
  29. count,
  30. success: async (res) => {
  31. try {
  32. const urls = []
  33. for (const path of res.tempFilePaths || []) {
  34. const data = await uploadFile(path, folder)
  35. if (data?.url) urls.push(data.url)
  36. }
  37. resolve(urls)
  38. } catch (e) {
  39. reject(e)
  40. }
  41. },
  42. fail: reject
  43. })
  44. })
  45. }