• 小程序uView2.X框架upload组件上传方法总结+避坑


    呈现效果:

    1.1单图片上传

    1.2多图片上传

    前言:相信很多人写小程序会用到uView框架,总体感觉还算OK吧,只能这么说,肯定也会遇到图片视频上传,如果用到这个upload组件相信你,肯定遇到各种各样的问题,这是我个人总结的单图片和多图片上传方法.

    uView2.X框架:uView 2.0 - 全面兼容 nvue 的 uni-app 生态框架 - uni-app UI 框架

    单图片上传:

    页面结构:

    1. "image1" ref="item">
    2. <view class="img">
    3. <u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="1"
    4. uploadIcon="plus" uploadIconColor="#0086ff" ref="upload" width="110" height="110">
    5. u-upload>
    6. <image v-if="!fileList1[0].url" src="../../../static/images/photo.png" mode="">image>
    7. view>
    8. <view class="text">(*请提供真实头像)view>

    1.首先定义的list 大家不要随便改,就按照官方的 

    1. fileList1: [],
    2. name="1" 标识符,

    2.分别有上传 删除  几个方法

    2.1删除方法

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

    2.2上传之前做的事情,比如 限制格式 限制大小 这点比较麻烦  ,里面注释写的比较详细

    1. // 新增图片 这个是上传图像的方法
    2. async afterRead(event) {
    3. // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
    4. let lists = [].concat(event.file)
    5. // 用于存储符合条件的图片
    6. let Images = [];
    7. // 遍历上传的每张图片
    8. for (let i = 0; i < lists.length; i++) {
    9. const item = lists[i];
    10. // 验证图片格式
    11. const isImage = /\.(png|jpe?g)$/i.test(item.url);
    12. if (!isImage) {
    13. uni.showToast({
    14. title: '只能上传png,jpg,jpeg格式的图片',
    15. icon: 'none',
    16. duration: 3000
    17. });
    18. // 删除不符合条件的图片
    19. lists.splice(i, 1);
    20. // 跳过当前图片,进行下一张图片的验证
    21. continue;
    22. }
    23. // 验证图片大小
    24. const maxSize = 2 * 1024 * 1024; // 2MB大小限制
    25. if (item.size > maxSize) {
    26. uni.showToast({
    27. title: '图片大小不能超过2MB',
    28. icon: 'none',
    29. duration: 3000
    30. });
    31. // 删除不符合条件的图片
    32. lists.splice(i, 1);
    33. // 跳过当前图片,进行下一张图片的验证
    34. continue;
    35. }
    36. Images.push(item)
    37. }
    38. let fileListLen = this[`fileList${event.name}`].length
    39. Images.map((item) => {
    40. this[`fileList${event.name}`].push({
    41. ...item,
    42. status: 'uploading',
    43. message: '上传中'
    44. })
    45. })
    46. for (let i = 0; i < Images.length; i++) {
    47. const result = await this.uploadFilePromise(Images[i].url)
    48. // 返回给后端服务器的 结果需要赋值给 this.infoForm.image = result
    49. console.log(result, '上传图像result');
    50. // this.infoForm.avatar = result
    51. let item = this[`fileList${event.name}`][fileListLen]
    52. this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
    53. status: result.status,
    54. message: result.status == 'failed' ? '上传失败' : '',
    55. url: result.url
    56. }))
    57. fileListLen++
    58. }
    59. },

    2.2.1 上传之前做了 格式和大小限制  如果不符合  直接删除 

    2.3 上传成功的回调   主要是是上传的是一个json格式 一定要进行处理   JSON.parse(res.data).path,

    而且这里做了状态判断  会有成功和失败判断  主要是上传失败可以叉掉  

    和这里进行状态对应处理 

    比较恶心的时候 不处理一直显示上传中  差不掉

    1. // 回调函数方法
    2. uploadFilePromise(url) {
    3. return new Promise((resolve, reject) => {
    4. let a = uni.uploadFile({
    5. url: baseUrl + '/admin/upload/targetFile', //后端接口地址
    6. filePath: url,
    7. name: 'file', //传给后端参数
    8. header: {
    9. 'token': uni.getStorageSync('whjk_token')
    10. },
    11. formData: {
    12. path: 'avatar/user'
    13. },
    14. success: (res) => {
    15. console.log(res, 'uploadFilePromise');
    16. // resolve(JSON.parse(res.data).path)
    17. if (res.statusCode == 200) {
    18. resolve({
    19. url: JSON.parse(res.data).path,
    20. status: 'success'
    21. })
    22. } else {
    23. resolve({
    24. url: url,
    25. status: 'failed'
    26. })
    27. }
    28. }
    29. });
    30. })
    31. },

    2.3传参说明  参数要 搞正确 

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

    多图片上传或者视频上传:

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

    其实上传方法都一样的 就是属性需要改一下就行  判断都是一样的方法

    1.需要修改这个属性

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

    2.页面结构

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

    3.上传前限制  大小  图片   格式   里面注释写的很详细

    1. // 视频image和pdf方法
    2. async imageOrVideoOrPdf(event) {
    3. console.log(event);
    4. // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
    5. let lists = [].concat(event.file);
    6. // 用于存储符合条件的图片
    7. let validImages = [];
    8. // 遍历上传的每张图片
    9. for (let i = 0; i < lists.length; i++) {
    10. const item = lists[i];
    11. // 验证图片格式
    12. const isImage = /\.(png|jpe?g)$/i.test(item.url);
    13. if (!isImage) {
    14. uni.showToast({
    15. title: '只能上传png,jpg,jpeg格式的图片!',
    16. icon: 'none',
    17. duration: 5000
    18. });
    19. // 删除不符合条件的图片
    20. lists.splice(i, 1);
    21. // 跳过当前图片,进行下一张图片的验证
    22. continue;
    23. }
    24. // 验证图片大小
    25. const maxSize = 2 * 1024 * 1024; // 2MB大小限制
    26. if (item.size > maxSize) {
    27. uni.showToast({
    28. title: '图片大小不能超过2MB!',
    29. icon: 'none',
    30. duration: 5000
    31. });
    32. // 删除不符合条件的图片
    33. lists.splice(i, 1);
    34. // 跳过当前图片,进行下一张图片的验证
    35. continue;
    36. }
    37. // 符合条件的图片添加到validImages数组中
    38. validImages.push(item);
    39. }
    40. let fileListLen = this[`fileList${event.name}`].length;
    41. validImages.map((item) => {
    42. this[`fileList${event.name}`].push({
    43. ...item,
    44. status: 'uploading',
    45. message: '上传中'
    46. })
    47. })
    48. for (let i = 0; i < validImages.length; i++) {
    49. const result = await this.uploadFileOrPdf(validImages[i].url);
    50. console.log(result);
    51. // 返回给后端服务器的结果需要赋值给 this.infoForm.annex = result
    52. let item = this[`fileList${event.name}`][fileListLen];
    53. // console.log(fileListLen);
    54. this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
    55. status: result.status,
    56. message: result.status == 'failed' ? '上传失败' : '',
    57. url: result
    58. }));
    59. console.log(result, 'result');
    60. if (result.status == 'success') {
    61. this.imgarr.push(result);
    62. console.log(this.imgarr,'imgarr');
    63. }
    64. fileListLen++;
    65. }
    66. // 将上传成功的url数组一起提交给后端
    67. // this.infoForm.annex = urls
    68. },

    4.上传成功回调   注释的地方有写  可以上传 pdf  视频  图片 改一下path路径就行  

    1. // 视频image和pdf方法回调函数
    2. uploadFileOrPdf(url) {
    3. // let uploadedFilePaths = [];
    4. return new Promise((resolve, reject) => {
    5. // let path;
    6. // const fileExtension = url.split('.').pop().toLowerCase();
    7. // if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
    8. // path = 'annex/image'; // 图片路径
    9. // } else if (fileExtension === 'pdf') {
    10. // path = 'annex/pdf'; // PDF路径
    11. // } else {
    12. // reject('Invalid file type');
    13. // return;
    14. // }
    15. uni.uploadFile({
    16. url: baseUrl + '/admin/upload/targetFile', //后端接口地址
    17. filePath: url,
    18. name: 'file', //传给后端参数
    19. header: {
    20. 'token': uni.getStorageSync('whjk_token')
    21. },
    22. formData: {
    23. path: 'annex/image' // 根据文件后缀类型设置路径
    24. },
    25. success: (res) => {
    26. console.log(res);
    27. // resolve(JSON.parse(res.data).path)
    28. if (res.statusCode == 200) {
    29. resolve({
    30. url: JSON.parse(res.data).path,
    31. status: 'success'
    32. })
    33. } else {
    34. resolve({
    35. url: url,
    36. status: 'failed'
    37. })
    38. }
    39. },
    40. fail: (err) => {
    41. // console.log(err,'err');
    42. reject(err);
    43. }
    44. });
    45. })
    46. },

    5.删除方法

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

    6.最终呈现的效果就是这样

  • 相关阅读:
    用两个栈实现队列
    数据链路层协议
    步力宝科技爆款产品定位,开创智能物联网新商业
    Linux 基本语句_编译C过程
    【行业科普】常见的边缘计算产品有哪些?主要应用于哪些场景?
    m基于自适应遗传优化的IEEE-6建设费用和网络损耗费用最小化电网规划算法matlab仿真
    力扣572 另一棵树的子树
    正则验证用户名和跨域postmessage
    Chrome速度无人能敌?Safari也甘拜下风
    Linux学习笔记15 - 多线程编程(二)
  • 原文地址:https://blog.csdn.net/shi15926lei/article/details/133776386