最近在做微信小程序,涉及到图片(多张)和视频(一条)上传到阿里云服务器,上传完阿里云服务器后再上传至应用服务器也就是公司的后台服务器,其过程也是有点复杂的,所以记录下。
开通oss服务和创建oss存储空间就不说了,配置跨域规则的相关工作后端已经完成了,由于我是负责前端部分的,所以我就从前端说起,如果你也是初次涉及此方面内容,请耐心看下去会帮助你解决问题的。话不多说,直接进入主题。
初次涉及,网上找了网页版的样例,试着了解下
解压打开index.html,长这样
找到upload.js把accessid, accesskey, host三个参数改成你的,这个失效时间可能是在index.html页面上传文件时显示403的原因之一。
打开代码示例中的index.html文件,上传文件到oss存储空间,通过浏览器查看请求信息,这里有两个参数是要用到小程序中上传文件的,我是先把这两个参数在小程序中调用测试可以上传成功了, 再走后面的流程的。但这只是测试,正常情况下需要通过调取后台接口获取上传文件所需的参数(fileName, policy, accessKeyId, signature,host)
接下来就是通过小程序上传图片到oss中了
在小程序中的测试流程:
upload: function(){
wx.chooseImage({
success: function (res) {
var tempFilePaths = res.tempFilePaths
console.log('chooseImage success, temp path is: ', tempFilePaths[0])
wx.uploadFile({
url: 'http://www.ieesee.cn',
filePath: tempFilePaths[0],
name: 'file',
formData: {
name: tempFilePaths[0],
key: "${filename}", 上传图片的名字和路径(默认路径根目录,自定义目录:xxx/xxx.png)
policy: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",//测试的网页版打开F12那获得
OSSAccessKeyId: "xxxxxxxxxxxxxxxx",
success_action_status: "200",
signature: "xxxxxxxxxxxxxxxxxxxxxxxxxx",//测试的网页版打开F12那获得
},
success: function (res) {
console.log('chooseImage success, temp path is: ', tempFilePaths[0])
wx.showToast({
title: "上传成功",
icon: 'success',
duration: 1000
})
},
fail: function ({errMsg}) {
console.log('upladImage fail, errMsg is: ', errMsg)
wx.showToast({
title: "上传失败",
duration: 1000
})
},
})
}
})
}
以上基本了解了微信小程序的上传到阿里云OSS的流程,下面开始走正式流程
----------------------------------------------------------------------------------------------------------------------------------------------------------------
界面就是先简单的写了两个按钮
调用接口获取上传文件所需参数:fileName, policy, accessKeyId, signature,host上传至阿里云,待全部文件上传完毕后再将上传至应用服务器(后台服务器)。
要注意的点:wx.uploadFile只能同时上传一个文件,不然会报错,网上很多都用的循环,但是本人亲测用for循环不行,上传的图片有重复的顺序也出现错误,但是问题还是有的,用递归上传完美解决。
/* 函数描述:作为上传文件时递归上传的函数体体;
* 参数描述:
* 内容类型 1:视频 2:图片
* tempFiles是文件路径数组
* successUp是成功上传的个数->0
* failUp是上传失败的个数->0
* i是文件路径数组的指标->0
* length是文件路径数组的长度
*/
//获取上传文件所需参数
getUploadInfo(contentType, tempFiles, successUp, failUp, i, length) {
var that = this;
var contentExt = tempFiles[i].tempFilePath.substr(tempFiles[i].tempFilePath.lastIndexOf('.') + 1);
var url = `${app.globalData.domain}/uploadContent/getOssUploadInfo`;
var data = {
uid: wx.getStorageSync("uid"),
openid: wx.getStorageSync("openId"),
contentType: contentType,
contentSubType: that.data.contentSubType,
contentExt: contentExt //图片类型:jpg. png ... 或者 视频类型:mp4.....
};
util.post(url, data).then((res) => {
if (res.data.retCode == 0) {
that.setData({
fileName: res.data.fileName,
policy: res.data.policy,
accessKeyId: res.data.accessKeyId,
signature: res.data.signature,
host: "https://" + res.data.host,
})
//获取完所需参数再选择文件上传
that.uploadFile(contentType, tempFiles, successUp, failUp, i, length);
} else {
wx.showModal({
title: '提示',
content: '[' + res.data.retCode + ']' + res.data.retMsg,
showCancel: false,
})
}
}).catch((error) => {
console.log(error);
})
},
//将文件上传到阿里云
uploadFile(contentType, tempFiles, successUp, failUp, i, length) {
var that = this;
wx.uploadFile({
url: that.data.host,
filePath: tempFiles[i].tempFilePath,
name: 'file',
formData: {
name: tempFiles[i].tempFilePath,
key: that.data.fileName, //上传图片的名字和路径(默认路径根目录,自定义目录:xxx/xxx.png)
policy: that.data.policy,
OSSAccessKeyId: that.data.accessKeyId,
success_action_status: "200",
signature: that.data.signature,
},
success: function (res) {
console.log(res);
successUp++;
wx.showToast({
title: "上传成功",
icon: 'success',
duration: 1000,
})
//已经上传完成的图片数组
var hasUploadedImgsArr = that.data.hasUploadedImgsArr;
var imgUrl = that.data.host + '/' + that.data.fileName;
hasUploadedImgsArr.push(imgUrl);
that.setData({
hasUploadedImgsArr: hasUploadedImgsArr
})
},
fail: function (errMsg) {
failUp++
console.log('upladImage fail, errMsg is: ', errMsg);
wx.showToast({
title: "上传失败",
duration: 1000
})
},
complete() {
i++;
if (i == length) {
//所有图片上传完成以后再上传至应用服务器
console.log('总共' + successUp + '张上传成功,' + failUp + '张上传失败!');
if (contentType == 1) { //1视频 2图片
that.submitVideo(); //将视频上传至应用服务器
} else { //图片
that.submitImage(); //将图片上传至应用服务器
}
} else {
//递归调用getUploadInfo函数
that.getUploadInfo(contentType, tempFiles, successUp, failUp, i, length);
}
}
})
},
//提交视频内容至应用服务器
submitVideo() {
var that = this;
var url = `${app.globalData.domain}/uploadContent/submitVideo`;
var data = {
uid: wx.getStorageSync("uid"),
openid: wx.getStorageSync("openId"),
videoTitle: "视频test",
videoUrl: this.data.host + '/' + this.data.fileName,
}
util.post(url, data).then((res) => {
that.setData({
hasUploadedImgsArr: []
})
if (res.data.retCode == 0) {
console.log("提交视频内容至应用服务器成功");
} else {
wx.showModal({
title: '提示',
content: '[' + res.data.retCode + ']' + res.data.retMsg,
showCancel: false,
})
}
}).catch((error) => {
console.log(error);
})
},
//提交图片至应用服务器
submitImage() {
var imageList = [],
listObj = null, that = this;
for (let i = 0; i < this.data.hasUploadedImgsArr.length; i++) {
listObj = {
"url": this.data.hasUploadedImgsArr[i],
"desc": `图片test${i + 1}`
};
imageList.push(listObj);
}
console.log(imageList);
var url = `${app.globalData.domain}/uploadContent/submitImage`;
var data = {
uid: wx.getStorageSync("uid"),
openid: wx.getStorageSync("openId"),
imageTitle: "上传图片test",
imageCover: imageList[0].url,
imageList: JSON.stringify(imageList)
}
util.post(url, data).then((res) => {
that.setData({
hasUploadedImgsArr: []
})
if (res.data.retCode == 0) {
console.log("提交图片至应用服务器成功");
} else {
wx.showModal({
title: '提示',
content: '[' + res.data.retCode + ']' + res.data.retMsg,
showCancel: false,
})
}
}).catch((error) => {
console.log(error);
})
},
//上传图片(多张)
uploadImage() {
console.log("上传图片。。。。");
this.setData({
contentSubType: 1
})
var that = this;
wx.chooseMedia({
count: 9,
mediaType: ['image'],
sourceType: ['album', 'camera'],
maxDuration: 30,
camera: 'back',
success: function (res) {
console.log(res);
var tempFiles = res.tempFiles;
that.setData({
imageFiles: tempFiles
})
var contentType = 2; //1视频 2图片
that.getUploadInfo(contentType, tempFiles, 0, 0, 0, tempFiles.length);
},
fail: function (error) {
console.log(error);
}
});
},
//上传视频(一条)
uploadVideo() {
this.setData({
contentSubType: 1
})
var that = this;
wx.chooseMedia({
count: 1,
mediaType: ['video'],
sourceType: ['album', 'camera'],
maxDuration: 30,
camera: 'back',
success: function (res) {
console.log(res);
var contentType = 1; //1视频 2图片
var tempFiles = res.tempFiles;
that.getUploadInfo(contentType, tempFiles, 0, 0, 0, tempFiles.length);
},
fail: function (error) {
console.log(error);
}
})
},
到这,流程就已经完了,功能也完成啦!