备注:
此上传方式为input[type=file]方式,非element-upload,如有element上传需求,请参照后篇antd的oss上传;
此上传方法稍显粗糙,临时用于企业微信上传图片方式的改造,大伙儿可以酌情优化;
Html部分:
<input @change="imgUpload" class="weui-uploader__input" name="file" type="file" accept="image/*" multiple/>
js部分:
获取policy:
getPolicyInfo() {
return new Promise((resolve,reject)=>{
getPolicyInfo({
notDialog: true
}).then((res) => {
if(res.code == 0) {
this.policyInfo = res.data
resolve()
}
})
})
},
图片上传:
imgUpload(event){
let that = this
let filesList = event.target.files
let oldLength = this.uploadedImgData.length
let length = filesList.length + oldLength
if(length > 9){
MessageBox({
message: "最多可上传9张,您还可以上传" + (9 - oldLength) + "张",
confirmButtonText:'确定',
confirmButtonClass: 'confirm-fontsize'
})
return false
}
Indicator.open({
text: '上传中...',
spinnerType: 'fading-circle'
})
for(let i = 0; i < filesList.length; i++) {
let imgSize = Math.floor(filesList[i].size / 1024)
if (imgSize > 3*1024*1024) {
MessageBox({
message: "请选择3M以内的图片!",
confirmButtonText:'确定',
confirmButtonClass: 'confirm-fontsize'
})
return false
}
this.nowImgNum++;
// oss逻辑
const imgFormat = filesList[i].name.split('.')[1];
const imgName = filesList[i].name.split('.')[0];
const imgMd5Name = this.$md5(imgName);
that.getPolicyInfo().then(()=>{
const {
host, OSSAccessKeyId, policy, signature
} = that.policyInfo
let formData = new FormData();
formData.append('OSSAccessKeyId', OSSAccessKeyId);
formData.append('policy', policy);
formData.append('signature', signature);
formData.append('Filename', '${filename}');
formData.append('key', `bbs/${imgMd5Name}.${imgFormat}`);
formData.append('success_action_status', '200');
formData.append('file', filesList[i]);
axios({
url: host,
header:{
'Content-Type': 'multipart/form-data'
},
method: 'post',
data: formData
})
.then(res => {
if(res.status===200){
let ossUrlList = [];
ossUrlList.push(`bbs/${imgMd5Name}.${imgFormat}`)
that.changeOssToId(ossUrlList)
}
})
});
// end
}
that.uploadImgNum = 9 - this.nowImgNum
if(that.uploadImgNum <= 0){
that.isUploadImg = false
}
},
备注:
1.依然注意key的传输方法和最后拼装渲染的数组;
2.最后的that.changeOssToId(ossUrlList)方法不用在意,后端当初企业微信三方应用开发遗留的老方式,有个localId换图片的概念,方法之前已完成oss上传所有逻辑;