图片、音频等文件上传自己的服务器会占用很多的资源,增加服务器的压力,这是后可以考虑上传到第三方,比如七牛云。上传七牛云首先要注册自己的七牛云账号,在此就不赘述。
获取七牛云token(需要后台去获取,暴露接口给前端)
调用小程序API获取图片,上传至七牛云
takePhoto() {
var that = this
wx.chooseImage({
count: 1,
sourceType: [‘camera’],
success: function(res) {
var filePath = res.tempFilePaths[0];
// 交给七牛上传
var date = new Date().getTime();
qiniuUploader.upload(filePath, (res) => {
// 每个文件上传成功后,处理相关的事情
// 其中 info 是文件上传成功后,服务端返回的json,形式如
// {
// “hash”: “Fh8xVqod2MQ1mocfI4S4KpRL6D98”,
// “key”: “gogopher.jpg”
// }
// 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
that.setData({
‘imageURL’: res.imageURL,
});
}, (error) => {
console.log(‘error: ‘ + error);
}, {
region: ‘ECN’,
domain: ‘https://yourUrl.com', // // bucket 域名,下载资源时用到。如果设置,会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
key: date + ‘.jpg’, // [非必须]自定义文件 key。如果不设置,默认为使用微信小程序 API 的临时文件名
// 以下方法三选一即可,优先级为:uptoken > uptokenURL > uptokenFunc
uptoken: that.data.uptoken, // 由其他程序生成七牛 uptoken//调用接口从后台获取的token
uptokenURL: that.data.uptoken, // 从指定 url 通过 HTTP GET 获取 uptoken,返回的格式必须是 json 且包含 uptoken 字段,例如: {“uptoken”: “[yourTokenString]”}
uptokenFunc: function() {
return that.data.uptoken;
}
}, (res) => {
// console.log(‘上传进度’, res.progress)
// console.log(‘已经上传的数据长度’, res.totalBytesSent)
// console.log(‘预期需要上传的数据总长度’, res.totalBytesExpectedToSend)
if (res.progress == 100) { //上传完成
}
});
},
fail: (res) => {
console.log(res)
}
})
}
音频的上传类似,需要配置一些音频相关的options
startAudio(){
var that=this
const options = {
duration: 30000, //指定录音的时长,单位 ms
sampleRate: 16000, //采样率
numberOfChannels: 1, //录音通道数
encodeBitRate: 96000, //编码码率
format: 'mp3', //音频格式,有效值 aac/mp3
frameSize: 50, //指定帧大小,单位 KB
}
//开始录音
recorderManager.start(options);
recorderManager.onStart(() => {
console.log('开始录音')
});
recorderManager.onStop((res) => {//停止录音
this.tempFilePath = res.tempFilePath;
console.log('停止录音', res.tempFilePath)
const {
tempFilePath
} = res
//上传七牛云
var filePath = res.tempFilePath;
// 交给七牛上传
var date = new Date().getTime();
qiniuUploader.upload(filePath, (res) => {
that.setData({
'audioUrl': res.imageURL,
});
}, (error) => {
console.log(res)
}, {
region: 'ECN',
domain: 'https://yourUrl.com',
key: date + '.mp3',
uptoken: that.data.uptoken,
uptokenURL: that.data.uptoken,
uptokenFunc: function() {
return that.data.uptoken;
}
}, (res) => {
if (res.progress == 100) { //上传完成
}
});
})
}
先分享到这里,如有其它问题可以参看七牛云的相关文档:
https://github.com/gpake/qiniu-wxapp-sdk