• 【Vant Weapp】van-uploader 文件上传


    目录

    图片上传

    图片回填

    修改样式

    循环多个上传图片

    自定义上传的控件


    图片上传

    未上传样式:

    上传限制6张后 :

     

    1. <van-uploader
    2. max-count="6"
    3. file-list="{{ fileList }}"
    4. bind:after-read="afterRead"
    5. bind:delete="delete"
    6. multiple="{{true}}"
    7. upload-text='上传图片'
    8. />

     fileList的图片要求的是全路径(http://xxxxx.com/xxxxx.png),而后端要求是去除域名(xxxxx.png),所以我另外封装了一个imgs数组。

    1. data: {
    2. fileList: [],
    3. imgs: [],
    4. baseUrl:"http://xxxxx.com"
    5. }
    1. afterRead(event) {
    2. const { file } = event.detail;
    3. let that = this
    4. // 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
    5. wx.uploadFile({
    6. url: 'http:xxxxx.com/upload',
    7. filePath: file[0].url,
    8. name: 'files',
    9. header: {
    10. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
    11. },
    12. formData: {},
    13. success: function (res) {
    14. // http://xxxxx.com/xxxxx.png
    15. const fileList = [...that.data.fileList]
    16. const url = 'http:xxxxx.com' + JSON.parse(res.data).data[0]
    17. fileList.push({url})
    18. // /xxxxx.png
    19. const imgs = [...that.data.imgs]
    20. imgs.push(JSON.parse(res.data).data[0])
    21. that.setData({
    22. imgs,
    23. fileList
    24. })
    25. },
    26. })
    27. },
    28. // 删除图片
    29. delete(e) {
    30. let idx = e.detail.index
    31. let fileList = this.data.fileList
    32. fileList.splice(idx, 1)
    33. let imgs = this.data.imgs
    34. imgs.splice(idx, 1)
    35. this.setData({
    36. fileList,
    37. imgs
    38. })
    39. },

    图片回填

    进入页面onload就要去调取接口,获取回填的数据。getPicture是获取数据的接口,可以自行换成自己的。

    后台返回:

    1. [
    2. {
    3. img:'/xxx.png',
    4. name:'xxx'
    5. }
    6. ]

     fileList需要的是:

    1. [
    2. {
    3. url:'/xxx.png',
    4. name:'xxx'
    5. }
    6. ]
    1. onLoad() {
    2. getPicture({
    3. id: this.data.id,
    4. }).then(res => {
    5. let imgs = []
    6. res.data.forEach((v) => {
    7. v.url = v.img // 接口中返回的名称,但是控件要求是url
    8. // 获取没有域名(/xxxxx.png)的数据。
    9. var reg = new RegExp(baseUrl,"g");
    10. var url = v.img.replace(reg,"");
    11. imgs.push(url)
    12. });
    13. this.setData({
    14. imgs,
    15. fileList: res.data
    16. })
    17. })
    18. }

    修改样式

    1. /*上传框*/
    2. .van-uploader .van-uploader__wrapper .van-uploader__upload {
    3. width: 160rpx !important;
    4. height: 160rpx !important;
    5. }
    6. /*小相机*/
    7. .van-uploader__upload-icon {
    8. font-size: 80rpx !important;
    9. }

    循环多个上传图片

    问题:由于afterRead无法传参,所以我在父级节点上添加点击事件。

    1. <view class="list">
    2. <view class="item" wx:for-items="{{list}}" wx:key="index">
    3. <view class="box" data-index="{{index}}" bind:tap="up">
    4. <van-uploader
    5. preview-size="200rpx"
    6. max-count="3"
    7. file-list="{{item.fileList}}"
    8. bind:after-read="afterRead"
    9. bind:delete="delete"
    10. multiple="{{true}}"
    11. upload-text='上传图片'
    12. />
    13. view>
    14. view>
    15. view>

     第一步:初始化的时候给list每一项添加fileList数组

    1. onLoad: function (options) {
    2. this.getList()
    3. },
    4. getList() {
    5. let id = this.data.id
    6. getList({ id }).then(res => {
    7. let list = res.data
    8. if(list && list.length>0) {
    9. list.forEach((v,k)=>{
    10. v.fileList = []
    11. })
    12. }
    13. this.setData({
    14. list
    15. })
    16. }).catch(err => {
    17. console.log(err)
    18. })
    19. },

    第二步:得到点击时的index

    1. up (e) {
    2. this.setData({
    3. idx: e.currentTarget.dataset.index
    4. })
    5. },

    第三步:上传成功后,压缩图片并且上传服务器。上传成功后,找到第index个fileList塞入图片。

    1. afterRead(event) {
    2. const that = this
    3. const { file} = event.detail;
    4. // 压缩图片
    5. wx.compressImage({
    6. src: file[0].url, //路径
    7. quality: 70, // 质量
    8. compressedWidth: 600,
    9. success(res){
    10. // 上传服务器
    11. wx.uploadFile({
    12. url: `http:xxxxx.com/commons/upload`,
    13. filePath: res.tempFilePath,//相当于file[0].url,
    14. name: 'files',
    15. header: {
    16. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
    17. },
    18. formData: {},
    19. success: function (res) {
    20. const list = that.data.list
    21. const fileList = list[that.data.idx].fileList
    22. fileList.push({
    23. url: 'http://xxxxx.com' + JSON.parse(res.data).data[0],
    24. name: '1'
    25. })
    26. that.setData({
    27. taskInfo: list
    28. })
    29. },
    30. fail: function (res) {}
    31. })
    32. },
    33. })
    34. },

    第四步:设置删除图片

    1. delete(e) {
    2. let that = this
    3. let index = e.detail.index
    4. const list = that.data.list
    5. const fileList = list[that.data.idx].fileList
    6. fileList.splice(index, 1)
    7. this.setData({
    8. list: list
    9. })
    10. },

    自定义上传的控件

    需求是点击右侧的加号,新增的图片在下方区域展示。

    问题一:

    第一步:参考Vant Weapp - uploader中自定义上传样式。将按钮改成加号图片。

    1. <view class="list">
    2. <view class="item" wx:for-items="{{list}}" wx:key='index' data-item='{{item}}'>
    3. <view class="box" style="display: flex; align-items: center;">
    4. <view class="name" style="margin-left: 10rpx">图片view>
    5. <van-uploader max-count="3" file-list="{{ item.fileList }}" bind:after-read="afterRead" bind:delete="delete" data-item="{{item}}" data-index="{{index}}">
    6. <image class="add" src="../../assets/images/add.png">image>
    7. van-uploader>
    8. view>
    9. <view class="img_list">
    10. <view class="img_box" wx:for-items="{{item.imgData}}" wx:key="item" wx:for-index="k" wx:for-item="v">
    11. <van-icon name="clear" class="close" catchtap='deleteImg' data-k="{{k}}" data-v="{{v}}" data-item="{{item}}" data-index="{{index}}"/>
    12. <image class="img" mode="aspectFit" src="{{'http://www.xxxx.com'+v}}" data-src="{{'http://www.xxxx.com'+v}}" data-item="{{item}}" alt="图片"/>
    13. view>
    14. view>
    15. view>
    16. view>

    第二步:上传图片后,控件默认上传后展示图片在加号的前面。

     这就导致了位置有偏移。最后只能自定义一个图片展示区域了。隐藏默认图片展示

    1. .van-uploader__preview {
    2. display: none!important;
    3. }

    第三步:初始化给每一项都添加fileList和imgList

    1. onLoad: function (options) {
    2. this.getList()
    3. },
    4. getList() {
    5. getList({id}).then(res => {
    6. res.data.forEach((v)=>{
    7. v.fileList = []
    8. v.imgData = []
    9. })
    10. this.setData({
    11. list: res.data
    12. })
    13. })
    14. }

     第四步:将上传成功的图片回填

    1. afterRead(event) {
    2. const that = this
    3. const { file} = event.detail;
    4. let index = that.data.index
    5. wx.uploadFile({
    6. url:'http://xxxxx.com/upload',
    7. filePath: res.tempFilePath,
    8. name: 'files',
    9. header: {
    10. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
    11. },
    12. formData: {},
    13. success: function (res) {
    14. let img = "list[" + index + "].fileList"
    15. var fileList = that.data.list[index].fileList;
    16. fileList.push({ url: res.tempFilePath})
    17. let imgs = that.data.list[index].imgData;
    18. imgs.push(JSON.parse(res.data).data[0])
    19. let image = "list[" + index + "].imgData"
    20. that.setData({
    21. [image]: image,
    22. [img]: fileList
    23. })
    24. },
    25. fail: function (res) {}
    26. })
    27. },

    第五步:删除图片

    1. deleteImg (e) {
    2. let that = this
    3. let index = e.currentTarget.dataset.index
    4. let idx = e.currentTarget.dataset.k
    5. let fileList = this.data.list[index].fileList
    6. fileList.splice(idx, 1)
    7. let file = "list[" + index + "].fileList"
    8. let imgs = this.data.list[index].imgData
    9. imgs.splice(idx, 1)
    10. let img = "list[" + index + "].imgData"
    11. this.setData({
    12. [file]:fileList,
    13. [img]: fileLists,
    14. })
    15. },

    图片上传前验证

    一定要记得加 use-before-read 哦。

    1. <van-uploader
    2. max-count="1"
    3. file-list="{{ fileList }}"
    4. use-before-read
    5. bind:before-read="beforeRead"
    6. multiple="{{false}}"
    7. upload-text='上传图片'
    8. />

    判断大小不能超过10M ,通过file.size判断。

    图片格式必须是.png和.jpg,通过file.url的后缀名判断。

    1. beforeRead(event) {
    2. const { file, callback } = event.detail;
    3. console.log(file)
    4. if (file.size > 10 * 1024 * 1024) {
    5. wx.showToast({
    6. title: '文件大小不能超过 10M!',
    7. icon: 'none'
    8. })
    9. callback(false);
    10. }
    11. let name = file.url.substring(file.url.lastIndexOf("."));
    12. if (name != '.png' && name != '.jpg') {
    13. wx.showToast({
    14. title: '图片必须是 .png 或 .jpg!',
    15. icon: 'none'
    16. })
    17. callback(false);
    18. }
    19. callback(true)
    20. },

    file的值

  • 相关阅读:
    windows 下使用 nvm use version 时报错 exit status 1
    javaee springMVC绑定复杂对象
    学习开发一个RISC-V上的操作系统(汪辰老师) — unrecognized opcode `csrr t0,mhartid‘报错问题
    【shell学习】企业运维工作中常用的shell脚本
    训练营第二十九天贪心(简单题目)
    redis(封装jedis)-----面试
    猜名次(附完整代码)
    双轴晶体中的锥形折射
    打字速度单位WPM、KPM定义与计算方法
    认证双软需要什么样的基本条件?
  • 原文地址:https://blog.csdn.net/wuli_youhouli/article/details/127787802