upload.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import {BASE_URL} from './request';
  2. /**
  3. * 上传图片
  4. * @param {string} filePath 本地文件路径
  5. * @param {string} url 上传接口路径(默认 /api/upload/image)
  6. * @param {string} name 后端接收文件字段名(默认 file)
  7. */
  8. export function uploadImage(filePath, url = '/api/upload/image', name = 'file') {
  9. return new Promise((resolve, reject) => {
  10. // wx.showLoading({
  11. // title: '上传中...',
  12. // mask: true
  13. // });
  14. wx.uploadFile({
  15. url: BASE_URL + url,
  16. filePath,
  17. name,
  18. header: {
  19. 'Authorization': wx.getStorageSync('token') || ''
  20. },
  21. success(res) {
  22. // wx.hideLoading();
  23. try {
  24. const data = JSON.parse(res.data);
  25. console.log(data)
  26. if (data.code === 200 && data.ret) {
  27. wx.showToast({
  28. title: '上传成功',
  29. icon: 'none'
  30. });
  31. resolve(data.data);
  32. } else {
  33. wx.showToast({
  34. title: data.message || '上传失败',
  35. icon: 'none'
  36. });
  37. reject(data);
  38. }
  39. } catch (err) {
  40. reject(err);
  41. }
  42. },
  43. fail(err) {
  44. // wx.hideLoading();
  45. wx.showToast({
  46. title: '网络异常,请重试',
  47. icon: 'none'
  48. });
  49. reject(err);
  50. }
  51. });
  52. });
  53. }