微信小程序图片上传并预览

先看效果:

图片预览:

代码如下:

wxml 

<view class="container">
   <button bindtap="chooseImageTap">上传图片</button>
   <view class="uploader__files">
      <block wx:for="{{picPaths}}" wx:key="*this">
         <view class="uploader__file" bindtap="previewImage" id="{{item}}">
            <image class="uploader__img" src="{{item}}" mode="aspectFill" />
         </view>
      </block>
   </view>
</view>

wxss

/**index.wxss**/
.uploader__file {
  float: left;
  margin-right: 8px;
  margin-bottom: 8px;
  width: 96px;
  height: 96px;
  background: no-repeat 50%;
  background-size: cover
}

.uploader__img {
  display: block;
  width: 100%;
  height: 100%;
}

js

// 获取应用实例
const app = getApp()

Page({
  data: {
    picPaths: []
  },
  //添加上传图片
  chooseImageTap: function () {
    var self = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'], // 按钮的文字数组,数组长度最大为 6
      itemColor: "#00000",             // 按钮的文字颜色
      success: function (res) {        // 接口调用成功的回调函数
        if (res.tapIndex == 0) {
          self.chooseWxImage('album');
        } else if (res.tapIndex == 1) {
          self.chooseWxImage('camera');
        }
      }
    })
  },
  // 图片本地路径
  chooseWxImage: function (type) {
    var self = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],   // 原图、压缩图
      sourceType: [type],                     // 选择图片的来源
      success: function (res) {
        // 下段注释代码可以先进行本地上传并预览
        // let picPaths = self.data.picPaths;
        // picPaths.push(res.tempFilePaths[0]);
        // self.setData({
        //  picPaths
        // })
        self.upImgs(res.tempFilePaths[0]) //调用上传方法
      }
    }) 
  },
  //上传服务器
  upImgs: function (imgurl) {
    var self = this;
    wx.uploadFile({
      url: '后端接口地址',   //后端接口地址
      filePath: imgurl,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data'
      },
      formData: null,
      success: function (res) {
        var data = JSON.parse(res.data);      //接口返回网络路径
        self.data.picPaths.push(data);
        self.setData({
          picPaths: self.data.picPaths
        })
      }
    })
  },
  // 图片预览
  previewImage: function(e){
    let picPaths = this.data.picPaths;
    wx.previewImage({
        current: e.currentTarget.id,   // 当前显示图片的http链接
        urls: picPaths                 // 需要预览的图片http链接列表
    })
  },
  onLoad() {
    
  }

})

使用了wx.showActionSheetwx.chooseImagewx.previewImage三个方法,我们依次来看下:

wx.showActionSheet

wx.chooseImage

wx.previewImage

参考资料: 

https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html

https://blog.csdn.net/weixin_42460570/article/details/81203206

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值