场景需求
需要在微信小程序里上传音频文件,音频文件需要直传阿里云OSS储存桶里
微信小程序选择文件方法
在普通的上传图片wx.chooseImage api是满足不了上传音频等文件的需求了。我们可以使用wx.chooseMessageFile 这个方法。选择微信聊天里的文件然后进行上传,这样就不限文件格式了。
以下是我将一个MP3文件上传选择流程。
![](https://i-blog.csdnimg.cn/blog_migrate/0f09e5772c70fd67364eb573bd86ee28.png)
![](https://i-blog.csdnimg.cn/blog_migrate/2395dc59231862877fd986e2afe446d0.png)
![](https://i-blog.csdnimg.cn/blog_migrate/4559d01f75201a01ad4c2b1655dbfa0f.png)
确定 之后打印出上传成功返回的数据
![](https://i-blog.csdnimg.cn/blog_migrate/901d1c79d84a343412d404503f7af552.png)
我们需要用到path临时路径将path路径上传给接口就完成文件上传了
微信小程序将文件上传到阿里云OSS
引用封装过的上传文件uploadAliyun.js
const uploadImage = require('../../utils/uploadToAliOss/uploadAliyun.js');
![](https://i-blog.csdnimg.cn/blog_migrate/63b5584ad006930ddd60089d68e52c2c.png)
![](https://i-blog.csdnimg.cn/blog_migrate/6838437cca8077ec4fe1c235243e414d.png)
upfile(){
var _this=this
wx.chooseMessageFile({
count: 1,
type: 'file',
success(rest) {
console.log(rest.tempFiles[0]);
var filePath=rest.tempFiles[0]
uploadImage({
filePath: rest.tempFiles[0],
dir: '', //上传的目录
success: function(res) {
_this.video=res
},
fail: function(res) {
console.log('上传失败---', res);
}
});
}
});
},
文件下载地址:https://download.csdn.net/download/qq_35946021/87578815
注意:
默认上传音频文件,如果是图片文件或其他文件uploadAliyun.js文件的filePath参数一点是临时路径,全局搜索 filePath: params.filePath.path有可能你们的参数不一样
config.js 内容更换成自己OSS配置信息
var fileHost = "https://xxxx.oss-cn-shanghai.aliyuncs.com"
OSSAccessKeyId: 'xxxx',
AccessKeySecret: 'xxxx',