官网地址:http://element.eleme.io/#/zh-CN/component/upload
1.引用element 上传控件。
<el-upload
action="/mgr/common/imgUpload"//这里需要配置一下文件上传地址(跨域)
list-type="picture-card"
accept="image/*"
:limit="imgLimit"
:file-list="productImgs"
:multiple="isMultiple"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:on-exceed="handleExceed"
:on-error="imgUploadError">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
2.js
export default {
data() {
return {
dialogImageUrl: '',
dialogVisible: false,
productImgs: [],
isMultiple: true,
imgLimit: 6
}
},
methods: {
handleRemove(file, fileList) {//移除图片
console.log(file, fileList);
},
handlePictureCardPreview(file) {//预览图片时调用
console.log(file);
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
beforeAvatarUpload(file) {//文件上传之前调用做一些拦截限制
console.log(file);
const isJPG = true;
// const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
// if (!isJPG) {
// this.$message.error('上传头像图片只能是 JPG 格式!');
// }
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
handleAvatarSuccess(res, file) {//图片上传成功
console.log(res);
console.log(file);
this.imageUrl = URL.createObjectURL(file.raw);
},
handleExceed(files, fileList) {//图片上传超过数量限制
this.$message.error('上传图片不能超过6张!');
console.log(file, fileList);
},
imgUploadError(err, file, fileList){//图片上传失败调用
console.log(err)
this.$message.error('上传图片失败!');
}
}
}
传单张:
<el-upload
class="avatar-uploader"
action="/api/v1/uploadImg"//注意跨域
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
<script>
export default {
data() {
return {
imageUrl: ''
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
}
</script>