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

效果图如下:

1487780-20190919082041888-1757407964.gif

wxml:


<view class="container">
<image class="image" src="{{imgPath}}" mode='scaleToFill' bindtap="previewImg"></image>
<button bindtap="selectImg">选择图片</button>
<button bindtap="loadImg">上传图片</button>
</view>

图片选择

wx.chooseImage(object)从相册中选择图片或是使用拍照

参数类型必填说明
countNumber最多可选择图片数量,默认9
sizeTypeStringArrayoriginal:原图;compressed:压缩图;默认两者都有
sourceTypeStringArrayalbum:从相册选择;camera:相机拍摄;默认两者都有
successFunction成功返回回调函数
failFunction失败回调函数
complateFunction完成回调函数

selectImg: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        //res.tempFilePaths 返回图片本地文件路径列表
        var tempFilePaths = res.tempFilePaths;
        that.setData({
          imgPath: tempFilePaths[0]
        })

      }
    })

  }

图片预览

wx.previewImage(object)预览图片

参数类型必填说明
currentString当前显示图片链接,不填默认urls第一张
urlsStringArray需要预览的图片链接列表
successFunction成功返回回调函数
failFunction失败回调函数
completeFunction完成回调函数

previewImg: function (e) {
    var img = this.data.imgPath;
    // 设置预览图片路径
    wx.previewImage({
      current: img,
      urls: [img]
    })
  }

图片上传

使用很早之前以前的JFinal上传时用的后端接口

Jfinal文件上传


loadImg: function () {
    var that = this;
    wx.uploadFile({
      url: "http://localhost:8080/upload/upload",
      filePath: that.data.imgPath,
      name: "upload_file",
      // 请求携带的额外form data
      /*formData: {
        "id": id
      },*/
      header: {
        'Content-Type': "multipart/form-data"
      },
      success: function (res) {
        wx.showToast({
          title: "图像上传成功!",
          icon: "",
          duration: 1500,
          mask: true
        });
      },
      fail: function (res) {
        wx.showToast({
          title: "上传失败,请检查网络或稍后重试。",
          icon: "none",
          duration: 1500,
          mask: true
        });
      }

    })
  }

转载于:https://www.cnblogs.com/chenjy1225/p/11546719.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值