上传图片,点击更换
做这种效果:
imgUrl判断显示那个样式
```
<el-form-item label="上传图片" v-model="imgUrl" class="items" prop="imgUrls">
<div v-show="!imgUrl">
<el-upload
action
list-type="picture-card"
:limit="1"
drag
:show-file-list="false"
:on-change="on_change"
accept=".jpg, .png"
:before-upload="onBeforeUpload"
:http-request="uploadFile"
:on-exceed="handlePicExceed"
>
<i slot="default" class="el-icon-plus">
<ul>
<li>拖拽或点击上传文件</li>
<li>支持扩展名:png、jpg</li>
</ul>
</i>
</el-upload>
</div>
<div v-show="imgUrl" style="width: 148px;height: 148px;position: relative;">
<input
type="file"
ref="input"
accept="image/png, image/jpeg, image/jpg"
style="display:none"
@change="Inputhange"
/>
<img
:src="imgUrl"
alt
width="148"
height="148px"
class="el-upload-list__item-thumbnail imgS"
/>
<span class="shade" @click="changeClick">点击更改</span>
</div>
</el-form-item>
```
点击input框更换图片
// 点击更改图片
changeClick() {
this.$refs.input.click();
},
Inputhange(e) {
console.log(e.target.files[0]);
this.files = e.target.files[0];
let form = new FormData();
// 后端接受参数 ,可以接受多个参数
form.append("file", this.files);
this.$post(
"",
form,
res => {
if (res.code === 1) {
this.$message.error(res.msg);
return;
}
this.imgUrl = res.data;
this.ruleForm.imgUrls = 2; // 验证图片
console.log(res);
},
err => {
this.$message.error(err.msg);
throw err;
}
);
},
el-upload中的事件
// 上传图片的change事件 on_change(file) { let isJPG = file.raw.type === "image/jpeg"; let isPNG = file.raw.type === "image/png"; // console.log(isPNG); if (isJPG || isPNG) { console.log(file); return; } this.$message.error("上传图片只能是 JPG 格式或PNG格式"); },
handlePicExceed() { this.$message({ message: "最多上传1张图片", type: "warning" }); },
// 上传前的钩子 onBeforeUpload(file) { // console.log(file); const isIMAGE = file.type === "image/jpeg" || file.type === "image/png"; // console.log(isIMAGE); if (!isIMAGE) { this.$message.error("上传文件只能是jpg,png格式!"); } return isIMAGE; },
// 自定义上传
uploadFile(file) {
console.log(file);
this.files = file.file;
let form = new FormData();
form.append("file", this.files);
this.$post(
"",
form,
res => {
if (res.code === 1) {
this.$message.error(res.msg);
return;
}
// this.imgUrl = res.data;
this.ruleForm.imgUrls = 2; // 验证图片
this.imgUrl = res.data;
console.log(res);
},
err => {
this.$message.error(err.msg);
throw err;
}
);
},