Analyzing Mini Program Uploaded Files

foreword

In the process of Mini Program development, if you involve uploading files, you need to use the API provided by WeChat to upload files:

wx.uploadFile()

The explanation of the official documentation will not be introduced here, mainly to see how this method is used and why it is used.

text

We can first look at the parameter description of the API:

In fact, the operation of wx.uploadFile is that you pass the data to be requested and the URL of the server to be requested to the WeChat server, and the WeChat server then takes the data to make a third-party server request. For details, please refer to the following figure:

So the url is the address where we usually request our own server interface. If your server needs to verify the session or token, you can add it in formData, for example, put the required uid in it:

 var formData = {
        uid: app.globalData.uid,
        sessionKey: wx.getStorageSync("SESSIONKEY")
      };

 

function upLoadFile(url, filePath, name, formData, success, fail) {
  
  wx.uploadFile({
    url: url,
    filePath: filePath,
    name: name,
    header: {
      'content-type': 'multipart/form-data'
    },
    formData:formData,     // Request additional form data 
    success: function (res) {
      console.log(res);
      if(res.statusCode ==200){
       typeof success == "function" && success(res.data);
      }else{
      typeof fail == "function" && fail(res.data);
      }
    },
    fail: function (res) {
      console.log(res);
      typeof fail == "function" && fail(res.data);
    }
  })
}

I directly encapsulate the uploaded file here. The WeChat server sends a data request to our server through the data we gave him. After the request is successful, the WeChat server will package the information returned by our own server and put it in res.data , so that we can directly get the feedback information from our server to us from res.data. 

 

Why do you want to do this? Instead of sending requests directly to our own server?

 Generally speaking, we directly call the interface of our own server, and then our own server returns the data applet. But in terms of uploadFile operation, it is actually the WeChat server that regards itself as a transit station, and all transmissions must be operated through WeChat transit. I personally think the reasons for this are as follows:

1. The WeChat server has its own set of temporary image links, which cannot be recognized by our own server.

2. In view of security considerations, the WeChat server will retain the pictures to ensure the legitimacy of the content on the WeChat platform.

 

If you have other reasons, please leave a message!

 

 

 

Reference documentation

1. Network request

Guess you like

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