Wechat applet development to get pictures from albums, use camera to take pictures and upload local pictures

Today, I encountered the user avatar setting function of the WeChat applet and took notes.

gif first:


Code again:

Small demo, the code is very simple.

1.index.wxml

<!--index.wxml-->
<button style="margin:30rpx;" bindtap="chooseimage">获取图片</button>
<image src="{{tempFilePaths }}" mode="aspecFill" style="width: 100%; height: 450rpx"/>

2.index.js

//index.js
//get application instance
var app = getApp ()
Page({
  data: {
    tempFilePaths: ''
  },
  onLoad: function () {
  },
  chooseimage: function () {
    var _this = this;
    wx.chooseImage({
      count: 1, // default 9
      sizeType: ['original', 'compressed'], // You can specify the original image or the compressed image, both by default
      sourceType: ['album', 'camera'], // You can specify whether the source is an album or a camera, both by default
      success: function (res) {
        // Returns a list of local file paths for the selected photo, tempFilePath can be used as the src attribute of the img tag to display the image
        _this.setData({
          tempFilePaths:res.tempFilePaths
        })
      }
    })
  }
})

API description:


Let's talk about sourcetype. The default is to get from the album and use the camera to take pictures. It is the same as WeChat's current interface for selecting pictures. The first box is to take pictures, and the latter is for album photos.

Note here: The returned image is the local path of the image. If you need to upload the image to the server, you need to use another API.

Sample code:

wx.chooseImage({
  success: function(res) {
    var tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'http://example.weixin.qq.com/upload', //just an example, not the real interface address
      filePath: tempFilePaths[0],
      name: 'file',
      formData:{
        'user': 'test'
      },
      success: function(res){
        var data = res.data
        //do something
      }
    })
  }
})

My blog: http://blog.csdn.net/qq_31383345


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325503741&siteId=291194637