upload.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. if (data.code === 200 && data.ret) {
  26. resolve(data.data);
  27. } else {
  28. wx.showToast({
  29. title: data.message || '上传失败',
  30. icon: 'none'
  31. });
  32. reject(data);
  33. }
  34. } catch (err) {
  35. reject(err);
  36. }
  37. },
  38. fail(err) {
  39. // wx.hideLoading();
  40. wx.showToast({
  41. title: '网络异常,请重试',
  42. icon: 'none'
  43. });
  44. reject(err);
  45. }
  46. });
  47. });
  48. }