- 使用element-ui中的el-upload上傳圖片
HTML:
<el-upload
class="avatar-uploader"
:headers="uploadHeader"
:action="UploadUrl()"
:show-file-list="false"
:on-error="uploadFail"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="addShufflingUrl" :src="addShufflingUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
data () {
return {
uploadHeader:{token:"5a041e7fc9da52000e1c5278"}
}
},
JS:
// 上傳接口
UploadUrl:function(){
return this.testDomain+"/images";
},
// 上傳之前
beforeAvatarUpload(file) {
// 圖片的類型
const imgType = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
// 圖片的大小
const imgSize = file.size / 1024 > 200 && file.size / 1024 < 500;
if (imgType != true) {
this.$message({message: "圖片上傳的格式不正確,中止上傳", type: "warning"});
}
if (!imgSize) {
this.$message({message: "圖片的大小必須在 200KB - 500KB 之間", type: "warning"});
}
return imgType && imgSize; // 若返回false,則中止上傳
},
// 圖片上傳成功
handleAvatarSuccess(res, file) {
this.addShufflingUrl = res.url;
},
// 圖片上傳失敗
uploadFail(err, file, fileList){
if(JSON.parse(err.message).code >= 400000){
alert(JSON.parse(err.message).code +" "+ " " + JSON.parse(err.message).message);
}
},
注意:
1. :headers="uploadHeader"為上傳時需要在請求頭里邊添加上對應的token雳刺。
uploadHeader:{token:"5a041e7fc9da52000e1c5278"}為對應的token的值崖技。
- UploadUrl為上傳接口劣砍,方便全局定義url時候調用