uploadImage.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import {
  2. apiUrl
  3. } from "../apis/apiConfig"
  4. function uploadFile(path, filePath, formData) {
  5. return new Promise((resolve, reject) => {
  6. wx.uploadFile({
  7. url: `${apiUrl}/${path}`,
  8. filePath,
  9. name: 'file',
  10. formData,
  11. success: e => {
  12. resolve(JSON.parse(e.data))
  13. },
  14. fail: reject
  15. })
  16. })
  17. }
  18. function uploadImage(path, params) {
  19. return new Promise((resolve, reject) => {
  20. wx.chooseMedia({
  21. mediaType: ["image"],
  22. sourceType: ["camera", "album"],
  23. success: e => {
  24. console.log("获取媒体成功!", e)
  25. let src = e.tempFiles[0].tempFilePath
  26. wx.compressImage({
  27. src,
  28. quality: 80, // 压缩质量
  29. success: async e => {
  30. console.log("图片压缩成功!", e)
  31. wx.hideLoading({
  32. success: (res) => {},
  33. })
  34. wx.showLoading({
  35. title: '正在上传...',
  36. })
  37. let res = await uploadFile(path, e.tempFilePath, params)
  38. console.log("上传结束", res)
  39. if (res.status == 0) {
  40. wx.showToast({
  41. title: res.msg
  42. })
  43. resolve(res)
  44. } else {
  45. wx.showToast({
  46. title: res.msg
  47. })
  48. }
  49. },
  50. fail: e => {
  51. console.log("失败2", e)
  52. }
  53. })
  54. },
  55. fail: e => {
  56. console.log("失败1", e)
  57. }
  58. })
  59. })
  60. }
  61. module.exports = {
  62. uploadFile,
  63. uploadImage
  64. }