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

效果图如下:

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)从相册中选择图片或是使用拍照

参数 类型 必填 说明
count Number 最多可选择图片数量,默认9
sizeType StringArray original:原图;compressed:压缩图;默认两者都有
sourceType StringArray album:从相册选择;camera:相机拍摄;默认两者都有
success Function 成功返回回调函数
fail Function 失败回调函数
complate Function 完成回调函数

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)预览图片

参数 类型 必填 说明
current String 当前显示图片链接,不填默认urls第一张
urls StringArray 需要预览的图片链接列表
success Function 成功返回回调函数
fail Function 失败回调函数
complete Function 完成回调函数

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
        });
      }

    })
  }

猜你喜欢

转载自www.cnblogs.com/chenjy1225/p/11546719.html