upload.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const { handleUpload } = require('../api/request')
  2. module.exports = {
  3. compressJs(file) {
  4. return new Promise(async (resolve, reject) => {
  5. try {
  6. const { errMsg, tempFilePath } = await wx.compressImage({
  7. src: file.filePath, // 图片路径
  8. quality: 80 // 压缩质量
  9. })
  10. if (errMsg === 'compressImage:ok') {
  11. resolve({ ...file, filePath: tempFilePath })
  12. return
  13. }
  14. resolve(file)
  15. } catch (err) {
  16. resolve(file)
  17. }
  18. })
  19. },
  20. async afterRead(event) {
  21. const { form } = this.data
  22. const { file } = event.detail
  23. const { formkey, maxsize = '2' } = event.currentTarget.dataset
  24. const maxSize = maxsize * 1024 * 1024
  25. let _file = file
  26. if (Object.prototype.toString.call(file) === '[object Object]') {
  27. _file = [file]
  28. }
  29. wx.showToast({
  30. title: '上传中',
  31. icon: 'loading',
  32. duration: 600 * 1000
  33. })
  34. const result = _file.map(async item => {
  35. // 压缩图片时传入的路径
  36. item.filePath = item.url
  37. item.formkey = formkey
  38. // item.url = ''
  39. const compressResult = item.size > maxSize ? await this.compressJs(item) : item
  40. return handleUpload(compressResult)
  41. })
  42. try {
  43. const res = await Promise.all(result)
  44. this.setData({
  45. ['form.' + formkey]: form[formkey].concat(...res)
  46. })
  47. wx.showToast({
  48. title: '上传成功',
  49. icon: 'success',
  50. duration: 2000
  51. })
  52. } catch (err) {
  53. wx.showToast({
  54. title: '上传出错',
  55. icon: 'none',
  56. duration: 2000
  57. })
  58. }
  59. },
  60. delete(event) {
  61. const { formkey } = event.currentTarget.dataset
  62. const { index } = event.detail
  63. this.data.form[formkey].splice(index, 1)
  64. this.setData({
  65. ['form.' + formkey]: this.data.form[formkey]
  66. })
  67. }
  68. }