1. 单张图片上传
第一次使用element的上传组件,总结一下希望能够帮助到大家,也便于自己以后使用。(大家可以根据自己所需来添加更改绑定的属性。)
<el-upload
class="avatar-uploader"
accept="image/jpeg"
:show-file-list="false"
:headers="{ token: token}"
:action="actionUrl"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img
v-if="ruleForm.dialogImageUrl"
:src="ruleForm.dialogImageUrl"
class="avatar"
/>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<div slot="tip" class="el-upload__tip">
只能上传jpg/png文件,且不超过50kb
</div>
</el-upload>
// 这里上传的时候需要在请求头重添加 token 我的项目的 token 在登陆之后,把 token 保存在了本地存储中,大家根据自己项目的实际情况添加token,
mounted () {
this.token = sessionStorage.getItem("tk");
this.actionUrl = this.common.data().shoppingMerchant + "/imageUpload/brand"; // 我的项目封装好的后台路径 根据自己项目的实际情况写
},
methods:{
handleAvatarSuccess (res, file) { // 上传成功后展示图片
this.ruleForm.dialogImageUrl = this.$baseImgUrl + res.data;
this.$set(this.ruleForm, this.ruleForm.dialogImageUrl, res.data)
},
beforeAvatarUpload (file) { // 上传前校验图片(根据自己项目的实际需求添加)
const imgType = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt50k = file.size / 1024 / 1024 < 0.048;
if (!imgType) {
this.$message.error('上传头像图片只能是 JPG和png 格式!');
return false
}
if (!isLt50k) {
this.$message.error('上传头像图片大小不能超过 50k!');
return false
}
}
}
2. 上传多张图片
<el-upload
class="upload"
:headers="{ token: token}"
:action="actionUrl"
list-type="picture-card"
:on-remove="handleDetailRemove"
:before-upload="handleDetailBefore"
:on-success="handleDetailSuccess"
:limit="5"
:file-list="detailImgList"
>
<i class="el-icon-plus"></i>
file-list 属性是个关键他有自己的数据结构 这里需要多注意(上传成功后图片有三个属性url,uid,status)
limit 限制上传几张图片
handleDetailRemove (file) { // 删除详情页图片
var vm = this;
var url = vm.common.data().shoppingMerchant + "/file/delFile"
var data = {
fileId: file.url
}
vm.common.shopGetData(vm, url, data, function (res) {
vm.detailImgList.forEach((item, index) => {
if (item.uid == file.uid) {
vm.detailImgList.splice(index, 1)
}
})
});
console.log(vm.detailImgList)
},
handleDetailBefore (file) { // 详情页图片上传大小类型限制
const imgType = file.type === 'image/png' || file.type == 'im
const isLt300k = file.size / 1024 / 1024 < 0.29;
if (!imgType) {
this.$message.error('上传图片只支持 jpg,png和jpeg 格式图片!
return false
}
if (!isLt300k) {
this.$message.error('上传图片大小不能超过 300k!');
return false
}
},
handleDetailSuccess (res, file) { // 上传成功后显示图片
if (res.returnCode == 10001) {
this.ruleForm.detailImages.push(res.data)
this.detailImgList.push({
url: this.$baseImgUrl + res.data,
uid: file.uid,
status: file.status
})
} else {
this.$message.error('详情页图片上传失败');
}
},