图片上传模块分享(七牛)
开发小程序避免不了使用CDN上传。分享我的小程序的七牛上传模块(外带wxlog(https://developers.weixin.qq.com/miniprogram/dev/framework/realtimelog/)实时日志上报)
// qiniuUploader.js
import configure from '../config'
import wxLog from './wxLog'
(function() {
let config = {
qiniuRegion: 'CDN所在地',
qiniuImageURLPrefix: 'CND前缀',
qiniuUploadToken: '测试用token',
}
module.exports = {
upload: upload
}
function upload (fileObject, options, qiniuUploadToken, progress, cancelTask) {
const filePath = fileObject.path
let tmpPromise = new Promise(function (resolve, reject) {
if (filePath == null) {
wxLog.warn(`qiniuUpload file path empty,${JSON.stringify(fileObject)}`)
reject(new Error('qiniu uploader need filePath to upload'))
}
if (qiniuUploadToken) {
config.qiniuUploadToken = qiniuUploadToken
}
// 小程序启动的时候获取token并设置
if (configure.qiniuUploadToken) {
config.qiniuUploadToken = configure.qiniuUploadToken
}
if (config.qiniuUploadToken) {
// 执行上传
if (config.qiniuUploadToken == null && config.qiniuUploadToken.length > 0) {
wxLog.warn(`qiniu UploadToken is null, please check the init config or networking`)
return
}
let url = uploadURLFromRegionCode(config.qiniuRegion)
let fileName = filePath.split('//')[1]
if (options && options.key) {
fileName = options.key
}
let formData = {
'token': config.qiniuUploadToken
}
// 设置文件名前缀
formData['key'] = 'wxmp/record/' + fileName
let uploadTask = wx.uploadFile({
url: url,
filePath: filePath,
name: 'file',
formData: formData,
success: function (res) {
if (res.error) {
wxLog.warn(res, `fileObject = ${JSON.stringify(fileObject)}`)
wxLog.setFilterMsg('qiniuUpload error')
reject(res.error)
}
let dataString = res.data
if (res.data.hasOwnProperty('type') && res.data.type === 'Buffer') {
dataString = String.fromCharCode.apply(null, res.data.data)
}
try {
let dataObject = JSON.parse(dataString)
let imageUrl = config.qiniuImageURLPrefix + '/' + dataObject.key
dataObject.resourceURL = imageUrl
wxLog.warn(`upload Success`, `${JSON.stringify(dataObject)}.fileObject = ${JSON.stringify(fileObject)}`)
resolve(dataObject)
} catch (e) {
wxLog.warn(e, `qiniuuploadTask success but parse JSON failed.fileObject = ${JSON.stringify(fileObject)}`)
console.log('parse JSON failed, origin String is: ' + dataString)
reject(e)
}
},
fail: function (error) {
wxLog.warn(error, `qiniuuploadTask fail.fileObject = ${JSON.stringify(fileObject)}`)
reject(error)
}
})
uploadTask.onProgressUpdate((res) => {
progress && progress(res)
})
cancelTask && cancelTask(() => {
wxLog.setFilterMsg('qiniuUpload cancel')
uploadTask.abort()
})
} else {
console.error('qiniu uploader need one of [uptoken]')
reject('qiniu uploader need one of [uptoken]')
}
})
return tmpPromise
}
// 科室用http://jssdk.demo.qiniu.io/performance测试上传速度
function uploadURLFromRegionCode(code) {
let uploadURL = null
switch (code) {
case 'ECN': uploadURL = 'https://upload.qiniup.com'; break// 华东
case 'NCN': uploadURL = 'https://up-z1.qbox.me'; break
case 'SCN': uploadURL = 'https://up-z2.qbox.me'; break
case 'NA': uploadURL = 'https://up-na0.qbox.me'; break
case 'ASG': uploadURL = 'https://up-as0.qbox.me'; break
default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]')
}
return uploadURL
}
})()
// index.js
import qiniu from '../qiniuUploader'
qiniu.upload({
path: tempRecordFilePath, // 图片文件路径
size: recordFileSize // 图片大小
}).then(res=>{
res.error // 若错误将返回错误
res.resourceURL // 返回的远程路径
})