需求:选取图片后,前端回显但不上传(不下载不入库),可修改删除,每次只允许上传一张图片,点击上传按钮再上传到服务器。
elementUI的坑:
1、官网给的大部分例子都是选图片后就直接上传,:before-upload方法定义上传文件前的钩子,在你选完图片后,就调用这个方法进行图片类型、大小等的判断,但如果你想让图片回显和上传动作分开的话需要设置:auto-upload="false"
关闭文件自动上传,但是关闭后发现不会触发before-upload方法,再次但是当你手动上传执行this.$refs.upload.submit();
这个方法时,才触发了before-upload上传前的钩子。
这个坑已经有解决方法了:用onChang方法
2、使用this.$refs.upload.clearFiles();
清空文件列表,实现覆盖文件上传,但是会导致this.$refs.upload.submit();
无效 (解决方法:去掉limit限制个数,通过fileList.splice(0,1) 每次取图片列表里最新的图片)
// 文件发生变化时的钩子
changePictureUpload(file) {
this.$refs.upload.clearFiles(); // 每次清空文件列表,就可以实现覆盖上传图片,但是只要有这行代码 this.$refs.upload.submit();就会失效。或者自己定义一个上传文件列表,清空文件列表也会使this.$refs.upload.submit();失效
...
},
// 自定义的上传方法
myUpload(val) {... },
onSubmit(file) {
console.log("file", file)
this.$refs.upload.submit(); // 此时调用myUpload()方法
},
以解决:
完整代码:
<el-form-item label="上传图片:" prop="url">
<el-upload
ref="upload"
class="pic-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:auto-upload="false"
:show-file-list="false"
:http-request="myUpload"
:on-change="changePictureUpload"
>
<img v-if="tempPic" :src="tempPic" class="picture">
<i v-else class="el-icon-plus pic-uploader-icon"></i>
</el-upload>
<el-col :span="24">
<span class="text_tip">允许上传图片格式:png/jpg,且图片大小不能超过2MB</span>
</el-col>
</el-form-item>
methods: {
//文件发生变化时的钩子
changePictureUpload(file,fileList) {
if (fileList.length > 1) {
fileList.splice(0,1)
}
// this.$refs.upload.clearFiles();
this.picInfo.name = file.raw.name.split(".")[0];
this.picInfo.type = file.raw.name.split(".")[1];
const isJPG = file.raw.type === 'image/jpeg';
const isPNG = file.raw.type === 'image/png';
const isLt2M = file.raw.size / 1024 / 1024 < 2;
this.tempPic = URL.createObjectURL(file.raw);
if (!isJPG && !isPNG) {
this.$message.error('上传图片格式不符合条件!');
this.tempPic = ''
this.picInfo.name = ''
this.picInfo.type = ''
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!');
this.tempPic = ''
this.picInfo.name = ''
this.picInfo.type = ''
}
// 返回图是jpg或png格式并且大小不超过2MB
return (isJPG || isPNG) && isLt2M;
},
// 自定义的上传方法
// 请求后台把图片上传到服务器,返回图片地址
myUpload(val) {
this.$nextTick(async () => {
// 以文件的格式传参
let fd = new FormData();
fd.append('file', val.file)
let params = {
url: '/fileUpload/pic',
param: fd
}
let res = await this.$store.dispatch('http/fileUpload', params)
console.log("res", res)
// 上传成功 返回码200
if(res.code==200){
this.picInfo.url = res.data
// 把图片地址入库保存
this.addPicInfo()
}else{
this.tempPic = ''
this.$message({message:'上传失败,请重新选择图片' ,type:'error'})
}
})
},
onSubmit() {
if (this.tempPic!= '') {
this.$refs.upload.submit();
} else {
this.$message({message: '请上传图片', type: 'error'})
return false
}
},
//保存图片信息
addPicInfo(){
this.$nextTick(async ()=>{
let params={
className:'Carousel',
method:'uploadCarousel',
param:this.picInfo
}
let res = await this.$store.dispatch('http/post',params)
if(res.code ==200){
this.$message({message: '提交成功', type: 'success'})
this.goBack()
}
})
},
}