備注:
此上傳方式為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上傳所有邏輯;
