How to upload audio and video to Baidu Cloud Bos cloud BCE in WeChat applet

After a series of investigations, no relevant articles have been found so far. Here, I briefly record the steps to solve this problem for the benefit of others.

My solution refers to the official documentation of Baidu Cloud BOS, the address is as follows:

https://cloud.baidu.com/doc/BOS/API.html#Object.E7.9B.B8.E5.85.B3.E6.8E.A5.E5.8F.A3

Upload using the wx.uploadFile interface.


Among them, special attention should be paid to:

Baidu Cloud uploads Objects through Post, and requires that a Policy must exist, and the Policy encoding format is UTF-8. The format of the Policy is as follows:

var policy = '{"expiration":"2018-05-01T12:00:00Z","conditions":[{"bucket":"your bucket name"},{"key":"The file is saved in BOS filename"}]}'
var base64 = base64.encode(policy)

By introducing Base64.js into the applet, the Policy can be easily converted to Base64 encoding. Next, this Base64 encoding needs to be encrypted by HmacSHA256.

signature = CryptoJS.HmacSHA256("Previous base64 encoded string", "Baidu Cloud's SK").toString(CryptoJS.enc.Hex)

At this point, the signature required for Baidu cloud upload has been obtained.

Next, you can call the API wx.uploadFile provided by the WeChat applet. The code is as follows:

wx.uploadFile({
  url: 'https://zhiyu.bj.bcebos.com',
  filePath: 'Take a picture. Or the full path returned by chooseImage, chooseVideo',
  name: 'file', // Note: this name must not be changed, must not be changed, must not be changed
  formData:{
	accessKey: 'ak provided by Baidu Cloud',
	policy: 'the base64 string mentioned above',
	signature: 'The signature mentioned above',
	key: 'The file name of the file saved in the BOS', // Note: This key must be consistent with the key in the policy, otherwise an error will be reported
	'Content-Type':'image/png' // You can not specify, BOS will automatically judge
  },
  success:function(res){
	var data = res.data
	console.log(res);
  },
  fail:function(res){
	console.log(res)
  }
})

With this process, you can easily upload photos and selected small videos directly from the WeChat applet to Baidu Cloud.

For the detailed code, please download the attachment, which contains the code for taking photos, recording small videos, and uploading photos to Baidu Cloud.

Attachment: How to upload audio and video to Baidu Cloud Bos cloud BCE via WeChat Mini Program


Guess you like

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