From 3b03f87a02458f719e2eb4bf112a13441b427d14 Mon Sep 17 00:00:00 2001
From: ‘chensiAb’ <‘chenchenco03@163.com’>
Date: Tue, 25 Mar 2025 13:54:34 +0800
Subject: [PATCH] Merge branch 'master' of ssh://dev.zhiheiot.com:29418/mob-components

---
 forms/imagePicker/CImagePicker.vue |  243 +++++++++++++++++++++++++-----------------------
 1 files changed, 125 insertions(+), 118 deletions(-)

diff --git a/forms/imagePicker/CImagePicker.vue b/forms/imagePicker/CImagePicker.vue
index 4d741be..e5f4238 100644
--- a/forms/imagePicker/CImagePicker.vue
+++ b/forms/imagePicker/CImagePicker.vue
@@ -1,5 +1,8 @@
 /**
  * CImagePicker
+ * 图片选择器组件,用于在表单中上传和管理图片
+ * 支持单张和多张图片上传,并提供压缩、预览等功能
+ * 可限制上传图片的数量和来源(相册/相机)
  * @author Tevin
  */
 
@@ -15,16 +18,18 @@
         <AtImagePicker
             ref="picker"
             mode="aspectFit"
+            :sourceType="sourceType"
             :multiple="count > 1"
             :count="count"
             :showAddBtn="!selectedFull"
             :length="3"
             :files="files"
-            :onChange="(files,operationType,index)=>handleChange(files,operationType,index)"
-            :onFail="evt=>handleFail(evt)"
-            :onImageClick="(index, file)=>handleImgView(index,file)"
+            :onChange="(files,operationType,index) => handleChange(files,operationType,index)"
+            :onFail="evt => handleFail(evt)"
+            :onImageClick="(index, file) => handleImgView(index,file)"
         />
         <CImageCompressor ref="compressor" />
+        <CImagePreview ref="imgPreview" />
     </view>
 </template>
 
@@ -36,12 +41,14 @@
 import { $fetchCommon } from '@fetchers/FCommon';
 import { Tools } from '@components/common/Tools';
 import CImageCompressor from './CImageCompressor.vue';
+import CImagePreview from './CImagePreview.vue';
 import './cImagePicker.scss';
 
 export default {
     name: 'CImagePicker',
     components: {
         CImageCompressor,
+        CImagePreview,
         AtInput,
         AtImagePicker,
         AtCurtain,
@@ -53,6 +60,26 @@
         count: {
             type: Number,
             default: 1,
+        },
+        // 图片来源
+        sourceType: {
+            type: Array,
+            default: () => ['album', 'camera'],
+        },
+        // 上传图片参数
+        params: {
+            type: Object,
+            default: () => {},
+        },
+        // 是否开启缩略图
+        needThumb: {
+            type: Boolean,
+            default: false,
+        },
+        // 上传地址来源
+        uploadUrlSource: {
+            type: String,
+            default: '',
         },
     },
     data() {
@@ -96,7 +123,7 @@
                     if (file.file && file.file.originalFileObj) {
                         if (
                             /image\/(gif|png|jpg|jpeg)/.test(
-                                file.file.originalFileObj.type
+                                file.file.originalFileObj.type,
                             )
                         ) {
                             return true;
@@ -119,8 +146,13 @@
                 const needs = nextFiles
                     .map((file, needIndex) => {
                         const fileInfo = file.file;
-                        // 没有 file 信息对象,或者不是 blob 类型
-                        if (!fileInfo || fileInfo.path.indexOf('blob') < 0) {
+                        // 没有 file 信息对象,或者不是 blob、wxfile、tmp 类型
+                        if (
+                            !fileInfo ||
+                            (fileInfo.path.indexOf('blob') < 0 &&
+                                fileInfo.path.indexOf('wxfile') < 0 &&
+                                fileInfo.path.indexOf('http://tmp/') < 0)
+                        ) {
                             return false;
                         }
                         // 尺寸小于 1M 的图片
@@ -158,7 +190,8 @@
             const urls = this.files
                 .map(file => (file.type === 'btn' ? false : file.url))
                 .filter(Boolean);
-            Taro.previewImage({
+            // 图片预览,支持H5模式下的双指缩放
+            this.$refs.imgPreview.$preview({
                 current: file.url, // 当前显示图片的http链接
                 urls, // 需要预览的图片http链接列表
             });
@@ -167,6 +200,9 @@
             this.showImg = false;
         },
         handleFail(msg) {
+            if (typeof msg === 'object') {
+                msg = msg.message;
+            }
             Taro.showToast({
                 title: msg,
                 icon: 'none',
@@ -183,95 +219,24 @@
                 file.fileName = this.fileNames[file.url];
                 files.push(file);
             });
-            uploadImage(files, (state, res) => {
-                if (state === 'success') {
-                    this.itemRes.onChange(res);
-                    setTimeout(() => {
-                        callback(state);
-                    }, 10);
-                } else if (state === 'error') {
-                    callback(state, res);
-                }
-            });
-            // let url = $fetchCommon.getUploadImgURL();
-            // if (url.indexOf('http') < 0) {
-            //     url = $hostBoot.getHost() + url;
-            // }
-            // const uploadTeam = [];
-            // const imgs = [];
-            // this.files.forEach(file => {
-            //     if (file.type === 'btn') {
-            //         return;
-            //     }
-            //     // 临时文件才上传
-            //     if (
-            //         file.url.indexOf('blob') >= 0 ||
-            //         file.url.indexOf('wxfile') >= 0 ||
-            //         file.url.indexOf('http://tmp/') >= 0
-            //     ) {
-            //         let header = {};
-            //         if (process.env.TARO_ENV === 'weapp') {
-            //             const localCookies = JSON.parse(
-            //                 Taro.getStorageSync('cookies') || '{}'
-            //             );
-            //             const cookiesArr = [];
-            //             Object.keys(localCookies).forEach(key => {
-            //                 cookiesArr.push(key + '=' + localCookies[key]);
-            //             });
-            //             header['Cookie'] = cookiesArr.join('; ');
-            //         }
-            //         uploadTeam.push(
-            //             new Promise((resolve, reject) => {
-            //                 Taro.uploadFile({
-            //                     url,
-            //                     header,
-            //                     filePath: file.url,
-            //                     fileName: this.fileNames[file.url],
-            //                     name: 'file',
-            //                     formData: {},
-            //                     success(res) {
-            //                         const res2 =
-            //                             typeof res.data === 'string'
-            //                                 ? JSON.parse(res.data)
-            //                                 : res.data;
-            //                         if (res2.state.code === 2000) {
-            //                             resolve(
-            //                                 $fetchCommon.transImgPath(
-            //                                     'fix',
-            //                                     res2.data.src ||
-            //                                         res2.data.file ||
-            //                                         res2.data.url
-            //                                 )
-            //                             );
-            //                         } else {
-            //                             reject({ message: res2.state.msg });
-            //                         }
-            //                     },
-            //                     cancel() {
-            //                         reject({ message: '上传图片已取消!' });
-            //                     },
-            //                     fail() {
-            //                         reject({ message: '上传图片失败!' });
-            //                     },
-            //                 });
-            //             })
-            //         );
-            //     }
-            //     // 其他类型视为 url,忽略
-            //     else {
-            //         uploadTeam.push(Promise.resolve(file.url));
-            //     }
-            // });
-            // Promise.all(uploadTeam)
-            //     .then(res => {
-            //         this.itemRes.onChange(res);
-            //         setTimeout(() => {
-            //             callback('success');
-            //         }, 0);
-            //     })
-            //     .catch(err => {
-            //         callback('error', err);
-            //     });
+            uploadImage(
+                files,
+                (state, res) => {
+                    if (state === 'success') {
+                        this.itemRes.onChange(res);
+                        setTimeout(() => {
+                            callback(state);
+                        }, 10);
+                    } else if (state === 'error') {
+                        callback(state, res);
+                    }
+                },
+                $fetchCommon.transKeyName('underline', {
+                    ...this.params,
+                    needThumb: this.needThumb ? 1 : 0,
+                }),
+                this.uploadUrlSource,
+            );
         },
     },
     mounted() {
@@ -287,11 +252,20 @@
     },
 };
 
-export const uploadImage = (files, callback) => {
+// 图片上传节流
+const _readyUpload = {};
+
+export const uploadImage = (files, callback, formData = {}, uploadUrlSource) => {
     if (!files || files.length === 0) {
         callback('success', []);
+        return;
     }
-    let url = $fetchCommon.getUploadImgURL();
+    let url = '';
+    if (uploadUrlSource === 'LPG') {
+        url = $fetchCommon.getLPGUploadImgURL();
+    } else {
+        url = $fetchCommon.getUploadImgURL();
+    }
     if (url.indexOf('http') < 0) {
         url = $hostBoot.getHost() + url;
     }
@@ -304,7 +278,7 @@
             file.url.indexOf('wxfile') >= 0 ||
             file.url.indexOf('http://tmp/') >= 0
         ) {
-            let header = {};
+            const header = {};
             if (process.env.TARO_ENV === 'weapp') {
                 const localCookies = JSON.parse(Taro.getStorageSync('cookies') || '{}');
                 const cookiesArr = [];
@@ -313,39 +287,72 @@
                 });
                 header['Cookie'] = cookiesArr.join('; ');
             }
+            const requestFile = {
+                url,
+                filePath: file.url,
+                fileName: file.fileName || '',
+            };
             uploadTeam.push(
                 new Promise((resolve, reject) => {
+                    // 如果本次已上传过,直接返回地址
+                    if (_readyUpload[file.url] && _readyUpload[file.url].length > 5) {
+                        resolve(_readyUpload[file.url]);
+                        return;
+                    }
+                    // 上传
                     Taro.uploadFile({
-                        url,
+                        ...requestFile,
                         header,
-                        filePath: file.url,
-                        fileName: file.fileName || '',
                         name: 'file',
-                        formData: {},
+                        formData,
+                        timeout: 30 * 1000,
                         success(res) {
-                            const res2 =
-                                typeof res.data === 'string'
-                                    ? JSON.parse(res.data)
-                                    : res.data;
+                            let res2;
+                            try {
+                                res2 =
+                                    typeof res.data === 'string'
+                                        ? JSON.parse(res.data)
+                                        : res.data;
+                            } catch (err) {
+                                reject({
+                                    ...requestFile,
+                                    response: res,
+                                    message: '上传图片异常!',
+                                });
+                                return;
+                            }
+                            // 上传成功
                             if (res2.state.code === 2000) {
-                                resolve(
-                                    $fetchCommon.transImgPath(
-                                        'fix',
-                                        res2.data.src || res2.data.file || res2.data.url
-                                    )
+                                const imgUrl = $fetchCommon.transImgPath(
+                                    'fix',
+                                    res2.data.src || res2.data.file || res2.data.url,
                                 );
-                            } else {
-                                reject({ message: res2.state.msg });
+                                _readyUpload[file.url] = imgUrl;
+                                resolve(imgUrl);
+                            }
+                            // 上传失败
+                            else {
+                                reject({
+                                    ...requestFile,
+                                    response: res2,
+                                    message: res2.state.msg,
+                                });
                             }
                         },
-                        cancel() {
-                            reject({ message: '上传图片已取消!' });
+                        cancel(err) {
+                            reject({
+                                ...requestFile,
+                                message: '上传图片已取消!',
+                            });
                         },
                         fail() {
-                            reject({ message: '上传图片失败!' });
+                            reject({
+                                ...requestFile,
+                                message: '上传图片失败!',
+                            });
                         },
                     });
-                })
+                }),
             );
         }
         // 其他类型视为 url,忽略

--
Gitblit v1.9.1