Summary of the upload method of the upload component of the small program uView2.X framework + pitfall avoidance

Presentation effect:

1.1 Single image upload

1.2 Multiple picture uploads

Foreword: I believe that many people will use the uView framework when writing small programs. The overall feeling is quite OK. I can only say this, and I will definitely encounter pictures and videos uploading. If I believe you will encounter various problems when using this upload component. This is my personal summary of single image and multiple image upload methods.

uView2.X framework:uView 2.0 - fully compatible with nvue's uni-app ecological framework - uni-app UI framework

Single image upload:

Page structure:

<u-form-item prop="image1" ref="item">
          <view class="img">

            <u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="1"
              uploadIcon="plus" uploadIconColor="#0086ff" ref="upload" width="110" height="110">
            </u-upload>

            <image v-if="!fileList1[0].url" src="../../../static/images/photo.png" mode=""></image>
          </view>
          <view class="text">(*请提供真实头像)</view>
        </u-form-item>

1. Don’t change the list defined first. Just follow the official one. 

fileList1: [],

name="1" 标识符,

2. There are several methods for uploading and deleting.

2.1Deletion method

// 图像删除方法
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
      },

2.2 Things to do before uploading, such as limiting the format and limiting the size. This is more troublesome. The comments in it are more detailed.

// 新增图片 这个是上传图像的方法
      async afterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
        let lists = [].concat(event.file)
        // 用于存储符合条件的图片
        let Images = [];
        // 遍历上传的每张图片
        for (let i = 0; i < lists.length; i++) {
          const item = lists[i];
          // 验证图片格式
          const isImage = /\.(png|jpe?g)$/i.test(item.url);
          if (!isImage) {
            uni.showToast({
              title: '只能上传png,jpg,jpeg格式的图片',
              icon: 'none',
              duration: 3000
            });
            // 删除不符合条件的图片
            lists.splice(i, 1);
            // 跳过当前图片,进行下一张图片的验证
            continue;
          }
          // 验证图片大小
          const maxSize = 2 * 1024 * 1024; // 2MB大小限制
          if (item.size > maxSize) {
            uni.showToast({
              title: '图片大小不能超过2MB',
              icon: 'none',
              duration: 3000
            });
            // 删除不符合条件的图片
            lists.splice(i, 1);
            // 跳过当前图片,进行下一张图片的验证
            continue;
          }
          Images.push(item)
        }


        let fileListLen = this[`fileList${event.name}`].length
        Images.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < Images.length; i++) {
          const result = await this.uploadFilePromise(Images[i].url)
          // 返回给后端服务器的 结果需要赋值给 this.infoForm.image = result
          console.log(result, '上传图像result');
          // this.infoForm.avatar = result
          let item = this[`fileList${event.name}`][fileListLen]
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: result.status,
            message: result.status == 'failed' ? '上传失败' : '',
            url: result.url
          }))
          fileListLen++
        }
      },

2.2.1 Make format and size restrictions before uploading. If they do not comply, delete them directly. 

2.3 The callback for successful upload is mainly because the upload is in a json format, which must be processed JSON.parse(res.data).path,

Moreover, status judgment is done here, and there will be success and failure judgments. Mainly, if the upload fails, it can be forked.  

Process the status accordingly here 

When it's disgusting, it keeps showing "Uploading" without processing.

// 回调函数方法
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: baseUrl + '/admin/upload/targetFile', //后端接口地址
            filePath: url,
            name: 'file', //传给后端参数
            header: {
              'token': uni.getStorageSync('whjk_token')
            },
            formData: {
              path: 'avatar/user'
            },
            success: (res) => {
              console.log(res, 'uploadFilePromise');
              // resolve(JSON.parse(res.data).path)
              if (res.statusCode == 200) { 
                resolve({
                  url: JSON.parse(res.data).path,
                  status: 'success'
                })
              } else {
                resolve({
                  url: url,
                  status: 'failed'
                })
              }
            }
          });
        })
      },

2.3 Instructions for passing parameters Parameters must be correct 

         uni.uploadFile({
            url: baseUrl + '/admin/upload/targetFile', // 后端接口地址
            filePath: url,
            name: 'file', //传给后端参数
            header: {
              'token': uni.getStorageSync('whjk_token')
            },
            formData: {
              path: 'avatar/user' // 后端给的路径 看情况而定
            },

Multiple image upload or video upload:

fileList2: [], //  不要随意定义
name = "2"

In fact, the uploading method is the same. It’s just that the attributes need to be changed. The judgment method is the same.

1. Need to modify this attribute

accept="image/*,video/*,.pdf"

2. Page structure

<u-form-item prop="annexPhoto" ref="item1">
          <view class="common">
            <text class="tex">展示附件</text>
            <text class="ext">(最多6个,仅支持png,jpg,jpeg格式上传)</text>
          </view>
          <view class="upload">
            <u-upload :fileList="fileList2" @afterRead="imageOrVideoOrPdf" @delete="deletePicPdf" name="2" multiple
               accept="image/*,video/*,.pdf"
              :maxCount="6" uploadIcon="plus" uploadIconColor="#0086ff" :deletable="true">
            </u-upload>
          </view>
        </u-form-item>

3. Limit the size and format of pictures before uploading. The comments inside are very detailed.

// 视频image和pdf方法
      async imageOrVideoOrPdf(event) {
        console.log(event);
        // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
        let lists = [].concat(event.file);
        // 用于存储符合条件的图片
        let validImages = [];
        // 遍历上传的每张图片
        for (let i = 0; i < lists.length; i++) {
          const item = lists[i];
          // 验证图片格式
          const isImage = /\.(png|jpe?g)$/i.test(item.url);
          if (!isImage) {
            uni.showToast({
              title: '只能上传png,jpg,jpeg格式的图片!',
              icon: 'none',
              duration: 5000
            });
            // 删除不符合条件的图片
            lists.splice(i, 1);
            // 跳过当前图片,进行下一张图片的验证
            continue;
          }
          // 验证图片大小
          const maxSize = 2 * 1024 * 1024; // 2MB大小限制
          if (item.size > maxSize) {
            uni.showToast({
              title: '图片大小不能超过2MB!',
              icon: 'none',
              duration: 5000
            });
            // 删除不符合条件的图片
            lists.splice(i, 1);
            // 跳过当前图片,进行下一张图片的验证
            continue;
          }
          // 符合条件的图片添加到validImages数组中
          validImages.push(item);
        }

        let fileListLen = this[`fileList${event.name}`].length;
        validImages.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })

        for (let i = 0; i < validImages.length; i++) {
          const result = await this.uploadFileOrPdf(validImages[i].url);
          console.log(result);
          // 返回给后端服务器的结果需要赋值给 this.infoForm.annex = result
          let item = this[`fileList${event.name}`][fileListLen];
          // console.log(fileListLen);
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: result.status,
            message: result.status == 'failed' ? '上传失败' : '',
            url: result
          }));
          console.log(result, 'result');
          if (result.status == 'success') {
            this.imgarr.push(result);
            console.log(this.imgarr,'imgarr');
          }
          fileListLen++;
        }
        // 将上传成功的url数组一起提交给后端
        // this.infoForm.annex = urls
      },

4. Upload success callback    There is a note in the comment area. You can upload pdf videos and pictures. Just change the path.  

// 视频image和pdf方法回调函数
      uploadFileOrPdf(url) {
        // let uploadedFilePaths = [];
        return new Promise((resolve, reject) => {
          // let path;
          // const fileExtension = url.split('.').pop().toLowerCase();
          // if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
          //   path = 'annex/image'; // 图片路径
          // } else if (fileExtension === 'pdf') {
          //   path = 'annex/pdf'; // PDF路径
          // } else {
          //   reject('Invalid file type');
          //   return;
          // }
          uni.uploadFile({
            url: baseUrl + '/admin/upload/targetFile', //后端接口地址
            filePath: url,
            name: 'file', //传给后端参数
            header: {
              'token': uni.getStorageSync('whjk_token')
            },
            formData: {
              path: 'annex/image' // 根据文件后缀类型设置路径
            },
            success: (res) => {
              console.log(res);
              // resolve(JSON.parse(res.data).path)
              if (res.statusCode == 200) {
                resolve({
                  url: JSON.parse(res.data).path,
                  status: 'success'
                })
              } else {
                resolve({
                  url: url,
                  status: 'failed'
                })
              }
            },
            fail: (err) => {
              // console.log(err,'err');
              reject(err);
            }

          });
        })
      },

5.Deletion method

 // 图像删除方法
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
      },

6.The final effect is like this

Guess you like

Origin blog.csdn.net/shi15926lei/article/details/133776386