There are two ways to upload photos by wechat mini program: one is to transfer the uploaded photos into Base64 and pass them to the back end; the other is to upload the photos to a cloud object service, such as Ali Cloud and Qiuniuyun, and then return the image storage path to the back end to reduce bandwidth.
Small program side:
1. Use an SDKGithub.com/gpake/qiniu…Qiniuuploader.js) where the storage is located, and then the secret key is in the 7 Cow cloud – personal center – secret key management (direct and back-end to)
(function () {
// Refer to the initQiniu() method in index.js of Demo. If options are assigned in use, the default value of config is not required. Init (options) is updateConfigWithOptions(options), which assigns a value to config
var config = {
// The bucket area. ECN, SCN, NCN, NA and ASG correspond to east China, South China, North China, North America and Singapore respectively
qiniuRegion: ' '.// the bucket prefix is used when downloading resources
qiniuBucketURLPrefix: ' '.// Select one of three methods to obtain a uptoken. The execution priority is upToken > uptokenURL > uptokenFunc. Choose one of three, and the other two are empty. UptokenURL is recommended, see readme.md for details
// The uptoken is generated by other programs and written directly to the uptoken
qiniuUploadToken: ' '.// Obtain the uptoken from the specified URL using HTTP GET. The returned format must be JSON and contain the uptoken field, for example: {" upToken ": "0MLvWPnyy..." }
qiniuUploadTokenURL: ' '.// uptokenFunc The value of this property can be a function used to generate a uptoken, see readme.md for details
qiniuUploadTokenFunction: function () {},/ / qiniuShouldUseQiniuFileName if it is true, then the key of the file will be qiniu server assigned to heavy (global). If false, the file key uses filename automatically generated by wechat. The default is false due to compatibility issues after the initial SDK users upgrade.
// wechat automatically generates a long filename, resulting in a long fileURL. It is recommended to use {qiniuShouldUseQiniuFileName: true} + "through fileURL download files, custom download name" combinations.
Two conditions are required to customize the upload key: 1. The value shouldUseQiniuFileName is false. 2. Modify the options parameter passed in the qiniuuploader. upload method to customize the key. (Please do not modify options parameters in SDK directly, please refer to index.js of demo for the modification method)
// When downloading files through fileURL, customize the download name. Please refer to: Seven NiuYun "object storage download download > > Settings > > product manual custom resource download name" (https://developer.qiniu.com/kodo/manual/1659/download-setting). This SDK is available in the "Frequently asked Questions" section of readme. md, with "Customize the download name when downloading files via fileURL".
qiniuShouldUseQiniuFileName: false
}
// init(options) initializes qiniuyun configuration into this SDK
// In the entire program life cycle, just init(options); At a time can be
// If you need to change the configuration, call init(options) again; Can be
function init(options) {
updateConfigWithOptions(options);
}
// Update the qiniu cloud configuration
function updateConfigWithOptions(options) {
if (options.region) {
config.qiniuRegion = options.region;
} else {
console.error('qiniu uploader need your bucket region');
}
if (options.uptoken) {
config.qiniuUploadToken = options.uptoken;
} else if (options.uptokenURL) {
config.qiniuUploadTokenURL = options.uptokenURL;
} else if (options.uptokenFunc) {
config.qiniuUploadTokenFunction = options.uptokenFunc;
}
if (options.domain) {
config.qiniuBucketURLPrefix = options.domain;
}
config.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName
}
// Do the pre-processing and apply the qiniuyun configuration
function upload(filePath, success, fail, options, progress, cancelTask) {
if (null == filePath) {
console.error('qiniu uploader need filePath to upload');
return;
}
if (options) {
updateConfigWithOptions(options);
}
if (config.qiniuUploadToken) {
doUpload(filePath, success, fail, options, progress, cancelTask);
} else if (config.qiniuUploadTokenURL) {
getQiniuToken(function () {
doUpload(filePath, success, fail, options, progress, cancelTask);
});
} else if (config.qiniuUploadTokenFunction) {
config.qiniuUploadToken = config.qiniuUploadTokenFunction();
if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
console.error('qiniu UploadTokenFunction result is null, please check the return value');
return
}
doUpload(filePath, success, fail, options, progress, cancelTask);
} else {
console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
return; }}// Upload officially
function doUpload(filePath, success, fail, options, progress, cancelTask) {
if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
console.error('qiniu UploadToken is null, please check the init config or networking');
return
}
var url = uploadURLFromRegionCode(config.qiniuRegion);
var fileName = filePath.split('/ /') [1];
// Customize the upload key (upload file name). You can customize the file name by modifying the options parameter passed in to the qiniuuploader.upload method. If options is not empty, the key in options is used as fileName
if (options && options.key) {
fileName = options.key;
}
var formData = {
'token': config.qiniuUploadToken
};
/ / qiniuShouldUseQiniuFileName if it is true, then the key of the file will be qiniu server assigned to heavy (global). If false, the file key uses filename automatically generated by wechat. The default is false due to compatibility issues after the initial SDK users upgrade.
if(! config.qiniuShouldUseQiniuFileName) { formData['key'] = fileName
}
var uploadTask = wx.uploadFile({
url: url,
filePath: filePath,
name: 'file'.formData: formData,
success: function (res) {
var dataString = res.data
// // this if case is a compatibility with wechat server returned a charcode, but was fixed
// if(res.data.hasOwnProperty('type') && res.data.type === 'Buffer'){
// dataString = String.fromCharCode.apply(null, res.data.data)
/ /}
try {
var dataObject = JSON.parse(dataString);
/ / stitching fileURL
var fileURL = config.qiniuBucketURLPrefix + '/' + dataObject.key;
dataObject.fileURL = fileURL;
// The imageURL field and the fileURL field are the same, but this SDK does not remove them, because the original version used imageURL. Direct deletion may cause an exception after the original user upgrades to the new SDK.
dataObject.imageURL = fileURL;
console.log(dataObject);
if(success) { success(dataObject); }}catch (e) {
console.log('parse JSON failed, origin String is: ' + dataString)
if(fail) { fail(e); }}},fail: function (error) {
console.error(error);
if(fail) { fail(error); }}})// File upload progress
uploadTask.onProgressUpdate((res) = > {
progress && progress(res)
})
// Interrupt file upload
cancelTask && cancelTask(() = > {
uploadTask.abort()
})
}
// Obtain the UpToken interface of Qiuniuyun. The URL is that the back-end server obtains the Uptoken interface of Qiuniuyun
function getQiniuToken(callback) {
wx.request({
url: config.qiniuUploadTokenURL,
success: function (res) {
var token = res.data.uptoken;
if (token && token.length > 0) {
config.qiniuUploadToken = token;
if(callback) { callback(); }}else {
console.error('qiniuUploader cannot get your token, please check the uptokenURL or server')}},fail: function (error) {
console.error('qiniu UploadToken is null, please check the init config or networking: '+ error); }})}// Select the file upload interface to transfer the file to the matching interface. ECN, SCN, NCN, NA and ASG correspond to east China, South China, North China, North America and Singapore respectively
function uploadURLFromRegionCode(code) {
var uploadURL = null;
switch (code) {
case 'ECN': uploadURL = 'https://up.qiniup.com'; break;
case 'NCN': uploadURL = 'https://up-z1.qiniup.com'; break;
case 'SCN': uploadURL = 'https://up-z2.qiniup.com'; break;
case 'NA': uploadURL = 'https://up-na0.qiniup.com'; break;
case 'ASG': uploadURL = 'https://up-as0.qiniup.com'; break;
default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
}
return uploadURL;
}
module.exports = {
init: init,
upload: upload,
}
})();
Copy the code
2. The mini program gets the token and uploads the picture using this SDK
const qiniuUploader = require('.. /.. /qiniuUploader.js')
Page({
data: {
imageURL:' '.uptoken:' '
},
test() {
wx.request({ / / get the token
url: 'http://localhost:4040/upload'.header: {
'Content-Type': 'application/json; charset=UTF-8'
},
method: 'get'.success: (response) = > {
this.setData({
uptoken: response.data.date
})
console.log(this.data.uptoken)
}
})
wx.chooseImage({ // get the temporary picture address
count: 1.sizeType: ['original'.'compressed'].sourceType: ['album'.'camera'].success:(res) = > {
// tempFilePath can display images as the SRC attribute of the IMG tag
const img = res.tempFilePaths[0]
// Upload to 7 ox
qiniuUploader.upload(img, (res) = > {
this.setData({
'imageURL': res.imageURL,
});
}, (error) = > {
console.log('error: ' + error);
}, {
region: 'SCN'./ / south China
domain: 'Your domain name'.//
key: 'customFileName.jpg'.// Upload the picture of seven niuyun is this name
// Select one of the following methods, whose priority is UpToken > uptokenURL > uptokenFunc
uptoken: this.data.uptoken, // Generate uptoken by other programs
uptokenURL: 'Storage space area'.// GET the upToken from the specified URL using HTTP. The returned format must be JSON and contain the upToken field, for example: {" upToken ": "[yourTokenString]"}
// uptokenFunc: function() {
// return '[yourTokenString]';
// }
}, (res) = > {
console.log('Upload Progress', res.progress)
console.log('Length of data uploaded', res.totalBytesSent)
console.log('Total length of data expected to be uploaded', res.totalBytesExpectedToSend)
}, () = > {
// Cancel upload
}, () = > {
// 'before' Operation performed before upload
}, (err) = > {
// 'complete' upload Operation performed after acceptance (performed regardless of success or failure)}); }})})}Copy the code