BucketName
(bucket name) and Region
(region name) specified. For more information, see Creating Buckets.examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com
.cos.ap-guangzhou.myqcloud.com
. For details, please refer to the comments in the code below.POST http://examplebucket-1250000000.cos.ap-beijing.myqcloud.com/
, and the requested domain name is the bucket domain name. In this way, if multiple storage buckets are used in the applet, you need to configure the bucket domain name as a whitelist domain name. The solution is as follows:POST http://cos.ap-beijing.myqcloud.com/examplebucket-1250000000/
, the requested domain name is the regional domain name, and the bucket name is placed in the requested path. To use multiple storage buckets in the same region in the applet, you only need to configure a domain name cos.ap-beijing.myqcloud.com
as the whitelist domain name./examplebucket-1250000000/
.var uploadFile = function () {// url encode format for encoding more charactersvar camSafeUrlEncode = function (str) {return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\\(/g, '%28').replace(/\\)/g, '%29').replace(/\\*/g, '%2A');};// get the signaturevar getAuthorization = function (options, callback) {wx.request({method: 'GET',// Replace it with your own server address to get the post upload signatureurl: 'http://127.0.0.1:3000/post-policy?ext=' + options.ext,dataType: 'json',success: function (result) {var data = result. data;if (data) {callback(data);} else {wx. showModal({title: 'Failed to obtain temporary key',content: JSON. stringify(data),showCancel: false,});}},error: function (err) {wx. showModal({title: 'Failed to obtain temporary key',content: JSON. stringify(err),showCancel: false,});},});};var postFile = function ({ prefix, filePath, key, formData }) {var requestTask = wx.uploadFile({url: prefix,name: 'file',filePath: filePath,formData: formData,success: function (res) {var url = prefix + '/' + camSafeUrlEncode(key).replace(/%2F/g, '/');if (res. statusCode === 200) {wx.showModal({ title: 'Uploaded successfully', content: url, showCancel: false });} else {wx. showModal({title: 'Upload failed',content: JSON. stringify(res),showCancel: false,});}console.log(res.header['x-cos-request-id']);console.log(res.statusCode);console.log(url);},fail: function (res) {wx. showModal({title: 'Upload failed',content: JSON. stringify(res),showCancel: false,});},});requestTask.onProgressUpdate(function (res) {console.log('Progress:', res);});};// upload filesvar uploadFile = function (filePath) {var extIndex = filePath. lastIndexOf('.');var fileExt = extIndex >= -1 ? filePath. substr(extIndex + 1) : '';getAuthorization({ ext: fileExt }, function (AuthData) {// Parameters used in the requestvar prefix = 'https://' + AuthData.cosHost;var key = AuthData.cosKey; // It is safer to let the server decide the file namevar formData = {key: key,success_action_status: 200,'Content-Type': '','q-sign-algorithm': AuthData.qSignAlgorithm,'q-ak': AuthData.qAk,'q-key-time': AuthData.qKeyTime,'q-signature': AuthData.qSignature,policy: AuthData. policy,};if (AuthData. securityToken)formData['x-cos-security-token'] = AuthData.securityToken;postFile({ prefix, filePath, key, formData });});};// Select a documentwx.chooseMedia({count: 1, // default 9sizeType: ['original'], // You can specify whether it is the original image or the compressed image, here the original image is used by defaultsourceType: ['album', 'camera'], // You can specify whether the source is an album or a camera, and the default is bothsuccess: function (res) {uploadFile(res. tempFiles[0]. tempFilePath);},});};
var uploadFile = function () {// url encode format for encoding more charactersvar camSafeUrlEncode = function (str) {return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\\(/g, '%28').replace(/\\)/g, '%29').replace(/\\*/g, '%2A');};// get the signaturevar getAuthorization = function (options, callback) {wx.request({method: 'GET',// Replace it with your own server address to get the put upload signatureurl: 'http://127.0.0.1:3000/put-sign?ext=' + options.ext,dataType: 'json',success: function (result) {var data = result. data;if (data) {callback(data);} else {wx. showModal({title: 'Failed to obtain temporary key',content: JSON. stringify(data),showCancel: false,});}},error: function (err) {wx. showModal({title: 'Failed to obtain temporary key',content: JSON. stringify(err),showCancel: false,});},});};var putFile = function ({ prefix, filePath, key, AuthData }) {// put upload needs to read the real content of the file to uploadconst wxfs = wx.getFileSystemManager();wxfs. readFile({filePath: filePath,success: function (fileRes) {var requestTask = wx. request({url: prefix + '/' + key,method: 'PUT',header: {Authorization: AuthData.authorization,'x-cos-security-token': AuthData.securityToken,},data: fileRes.data,success: function success(res) {var url = prefix + '/' + camSafeUrlEncode(key).replace(/%2F/g, '/');if (res. statusCode === 200) {wx. showModal({title: 'Uploaded successfully',content: url,showCancel: false,});} else {wx. showModal({title: 'Upload failed',content: JSON. stringify(res),showCancel: false,});}console.log(res.statusCode);console.log(url);},fail: function fail(res) {wx. showModal({title: 'Upload failed',content: JSON. stringify(res),showCancel: false,});},});requestTask.onProgressUpdate(function (res) {console.log('Progress:', res);});},});};// upload filesvar uploadFile = function (filePath) {var extIndex = filePath. lastIndexOf('.');var fileExt = extIndex >= -1 ? filePath. substr(extIndex + 1) : '';getAuthorization({ ext: fileExt }, function (AuthData) {const prefix = 'https://' + AuthData.cosHost;const key = AuthData. cosKey;putFile({ prefix, filePath, key, AuthData });});};// Select a documentwx.chooseMedia({count: 1, // default 9sizeType: ['original'], // You can specify whether it is the original image or the compressed image, here the original image is used by defaultsourceType: ['album', 'camera'], // You can specify whether the source is an album or a camera, and the default is bothsuccess: function (res) {uploadFile(res. tempFiles[0]. tempFilePath);},});};
Was this page helpful?