微信小程序教程-图片上传

效果图:

wxml代码:

<!--demo picUpload-->
<text>demo_pages/picUpload/picUpload.wxml</text>
<button bindtap="insertImage">上传</button>
<image class="" src="{{src}}" mode="aspectFill"></image>

js.代码:

// demo_pages/picUpload/picUpload.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  //插入图片事件监听
  insertImage() {
    var _this = this;
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#00000",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage_editor('album')
          } else if (res.tapIndex == 1) {
            that.chooseWxImage_editor('camera')
          }
        }
      }
    })
  },
  // 选择图片本地路径
  chooseWxImage_editor: function (type) {
    var that = this;
    var imgsPaths = that.data.imgs;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
        console.log(res.tempFilePaths[0]);
        that.upImgs_editor(res.tempFilePaths[0], 0) //调用上传方法
      }
    })
  },
  /**编辑器图片上传至服务器**/
  upImgs_editor: function (imgurl, index) {
    var that = this;
    var _this = this;
    wx.uploadFile({
      url: 'https://jorian.image.cn/fileUpload',//注意填写自己的服务器地址
      filePath: imgurl,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data'
      },
      formData: null,
      success: function (res) {
        var resj = JSON.parse(res.data);
        console.log(resj) //接口返回网络 
        var src = resj.data.url
        _this.setData({
          src:src
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值