微信小程序图片上传并展示,vant组件+wx.uploadFile

微信小程序图片上传并展示,vant组件+wx.uploadFile

实现功能:图片展示+上传服务器+删除

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d5ygJP7G-1675862851707)(C:\Users\28132\AppData\Roaming\Typora\typora-user-images\1675862815144.png)]

//xwml部分: vant的Uploader功能 
<van-cell use-label-slot custom-style="padding-bottom: 0" title="问题附件" border="{
    
    {false}}">
        <view class="uploader" slot="label" style="margin-top: 20rpx;">
          <van-uploader bind:after-read="getAttachment"  bind:delete="delAttachment" deletable="{
    
    {true}}" preview-size="100" file-list="{
    
    { attachment }}" />
        </view>
      </van-cell>

<van-uploader> 组件 图片上传

  • bind:after-read 事件 选中图片触发的事件

  • deletable 开启右上角的删除按钮,默认是true

  • bind:delete 删除触发的事件

  • file-list 遍历的图片 是数组对象类型 :通过向组件传入file-list属性,可以绑定已经上传的图片列表,并展示图片列表的预览图,以下是filelist的结构:

    •  fileList: [
            {
               
               
              url: 'https://img.yzcdn.cn/vant/leaf.jpg',
              name: '图片1',
            },
            // Uploader 根据文件后缀来判断是否为图片文件
            // 如果图片 URL 中不包含类型信息,可以添加 isImage 标记来声明
            {
               
               
              url: 'http://iph.href.lu/60x60?text=default',
              name: '图片2',
              isImage: true,
              deletable: true,
            },
          ],
      

js部分: 配合微信小程序的上传文件API完成图片的上传

	data:{
    
    
	 attachment: [],
	},
 // 获取上传的照片
  getAttachment({
     
      detail: {
     
      file } }) {
    
    
    wx.uploadFile({
    
    
      url: wx.http.baseURL + '/upload', 
      filePath: file.url,
      name: 'file',
      header: {
    
    
        Authorization: 'Bearer ' + getApp().token
      },
      success: (res) => {
    
    
        this.data.attachment.push(JSON.parse(res.data).data)
        this.setData({
    
    
          attachment: this.data.attachment
        })
      }
    })
  },
      
//删除
  delAttachment({
     
      detail }) {
    
    
    const attachment = this.data.attachment.filter((item, index) => index !== detail.index)
    this.setData({
    
    
      attachment
    })
  },      

wx.uploadFile 是微信小程序提供的API ,用于将本地资源上传到服务器.

官方地址:
https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html

  1. 在成功的回调函数里注意返回的res.data是字符串,这里需要用JSON.parse转换成对象
  2. 由于attachment在data中是数组,这里需要将每一次上传的图片的信息(对象)存入进去,我这里用push推入数组,由于此时往数据添加数据,由于是单向数据流,所以后面又用了this.setData来模拟双向数据流绑定
  3. 在删除时,delete方法提供的回调里有删除的index可以让我们来对数组进行操作,这里用filter过滤来处理
    1. 官网地址:https://vant-contrib.gitee.io/vant-weapp/#/uploader

猜你喜欢

转载自blog.csdn.net/qq_40797578/article/details/128943833