WeChat applet realizes file and image upload

In my opinion, the functions of WeChat Mini Programs are quite powerful, providing many APIs for you to use directly.

Here I will talk about how the WeChat applet realizes the upload of pictures

1. Set the legal domain name of uploadFile on the WeChat official account platform

Click Settings - Development Settings, you can see the server domain name, click Modify, and set the legitimate domain name of your uploadFile.

Otherwise the following error will appear.



2. Use wx.chooseImage and wx.uploadFile to upload images

code show as below

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
        var tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: 'https://...', //replace your interface address here
          filePath: tempFilePaths[0],
          name: 'img',
          header: {  
            "Content-Type": "multipart/form-data",
            'accept': 'application/json',
            'Authorization': 'Bearer ..' //If there is a token, replace your token here, if not, omit it
          },
          formData:{
	    'user':'test' //Other additional formdata, don't write
          },
          success: function(res){
            var data = res.data;
	    console.log('data');
          },
          fail: function(res){
            console.log('fail');

          },
        })
      }
    })

Note: At present, the WeChat applet does not support base64 image uploading




Guess you like

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