Ver código fonte

贷款-新增图片压缩功能

panyong 4 anos atrás
pai
commit
6beffadf34

+ 28 - 3
htmldev/loan/src/views/loan/attest/components/myUploader.vue

@@ -8,6 +8,7 @@
 <script>
   import { Uploader, Toast } from 'vant'
   import { uploadFile } from '../../../../api/common'
+  import Compressor from 'compressorjs'
 
   export default {
     name: 'myUploader',
@@ -26,6 +27,7 @@
     },
     data () {
       return {
+        Compressor: null,
         arrUploadFile: []
       }
     },
@@ -44,11 +46,15 @@
       },
       afterRead (file) {
         const fileList = Array.isArray(file) ? file : [file]
-        const result = fileList.map(item => this.funUploadImg(item.file))
         fileList.forEach(item => {
           item.status = 'uploading'
           item.message = '上传中...'
         })
+        const result = fileList.map(async item => {
+          const maxSize = 2 * 1024 * 1024
+          const compressResult = item.file.size > maxSize ? await this.funCompressor(item.file) : item.file
+          return this.funUploadImg(compressResult)
+        })
         Promise.all(result).then(res => {
           res.forEach((item, index) => {
             if (item.filePath && item.filePath.startsWith('http')) {
@@ -58,10 +64,26 @@
             fileList[index].message = ''
             this.$emit('funSetUploadData', this.uploadType, this.arrUploadFile)
           })
-        }).catch(() => {
+        }).catch(err => {
           fileList.forEach(item => {
             item.status = 'failed'
-            item.message = '上传失败'
+            item.message = err
+          })
+        })
+      },
+      funCompressor (file) {
+        return new Promise((resolve, reject) => {
+          this.Compressor = new Compressor(file, {
+            quality: 0.6,
+            success (result) {
+              resolve(result)
+            },
+            error (err) {
+              try {
+                reject(err)
+              } catch (e) {
+              }
+            }
           })
         })
       },
@@ -77,6 +99,9 @@
           })
         })
       }
+    },
+    beforeDestroy () {
+      this.Compressor = null
     }
   }
 </script>