123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- const { handleUpload } = require('../api/request')
- module.exports = {
- compressJs(file) {
- return new Promise(async (resolve, reject) => {
- try {
- const { errMsg, tempFilePath } = await wx.compressImage({
- src: file.filePath, // 图片路径
- quality: 80 // 压缩质量
- })
- if (errMsg === 'compressImage:ok') {
- resolve({ ...file, filePath: tempFilePath })
- return
- }
- resolve(file)
- } catch (err) {
- resolve(file)
- }
- })
- },
- async afterRead(event) {
- const { file } = event.detail
- const { formkey, maxsize = '2' } = event.currentTarget.dataset
- const maxSize = maxsize * 1024 * 1024
- let _file = file
- if (Object.prototype.toString.call(file) === '[object Object]') {
- _file = [file]
- }
- wx.showToast({
- title: '上传中',
- icon: 'loading',
- duration: 200000
- })
- const result = _file.map(async item => {
- // 压缩图片时传入的路径
- item.filePath = item.url
- item.formkey = formkey
- const compressResult = item.size > maxSize ? await this.compressJs(item) : item
- return handleUpload(compressResult)
- })
- try {
- const res = await Promise.all(result)
- if (this.uploadCallBack) {
- this.uploadCallBack(res)
- }
- wx.showToast({
- title: '上传成功',
- icon: 'success',
- duration: 2000
- })
- } catch (err) {
- console.log(err)
- wx.showToast({
- title: '上传出错',
- icon: 'none',
- duration: 2000
- })
- }
- },
- delete(event) {
- const { formkey } = event.currentTarget.dataset
- const { index } = event.detail
- const temp = JSON.parse(JSON.stringify(this.data.form[formkey]))
- temp.splice(index, 1)
- this.setData({
- [`form.${formkey}`]: temp
- })
- },
- async uploadImg(event) {
- const { formkey, maxsize = '2' } = event.currentTarget.dataset
- const maxSize = maxsize * 1024 * 1024
- try {
- const { errMsg, tempFiles } = await wx.chooseImage({
- count: 1,
- sizeType: ['original', 'compressed']
- })
- if (errMsg === 'chooseImage:ok') {
- wx.showToast({
- title: '上传中',
- icon: 'loading',
- duration: 200000
- })
- const result = tempFiles.map(async item => {
- item.filePath = item.path
- item.formkey = formkey
- const compressResult = item.size > maxSize ? await this.compressJs(item) : item
- return handleUpload(compressResult)
- })
- try {
- const res = await Promise.all(result)
- if (this.uploadCallBack) {
- this.uploadCallBack(res)
- }
- wx.showToast({
- title: '图片上传成功',
- icon: 'success',
- duration: 2000
- })
- } catch (err) {
- console.log(err)
- wx.showToast({
- title: '图片上传出错',
- icon: 'error',
- duration: 2000
- })
- }
- }
- } catch (e) {
- }
- }
- }
|