在页面点击两次立即捐赠按钮,图片路径才能保存进数据库,按一次按钮不行,刷新之后再按也不行。请问是哪里的代码有问题啊?
前端
<el-row>
<el-col :span="8">
<el-form-item label="物资图片" prop="unit">
<el-upload
accept="image/jpeg,image/png"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
ref="upload"
action=""
:http-request="upload"
:auto-upload="false"
:before-upload="onBeforeUpload"
multiple
:limit="1"
:on-exceed="handleExceed"
v-model="addForm.pictures">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过1M</div>
</el-upload>
</el-form-item>
</el-col>
</el-row>
<el-form-item>
<el-button type="primary" @click="addIn">立即捐赠</el-button>
</el-form-item>
methods:{
addIn() {
this.$refs.upload.submit();
this.$refs.addFormRef.validate(async valid => {
if (!valid) return;
const {data: res} = await this.$http.post("addIn2", this.addForm);
if (res != "success") {
return this.$message.error("捐赠失败~");
}
this.$message.success("捐赠成功~");
console.log(this.addForm);
this.addDialogVisible = false;
});
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${ file.name }?`);
},
onBeforeUpload(file)
{
const isIMAGE = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt1M = file.size / 1024 / 1024 < 1;
if (!isIMAGE) {
this.$message.error('上传文件只能是图片格式!');
return false;
}
if (!isLt1M) {
this.$message.error('上传文件大小不能超过 1MB!');
return false;
}
return true;
},
upload (file) {
const _this = this
let formdata = new FormData()
// 上传图片并返回路径
formdata.append('pictures', file.file)
_this.$http.post('/api/uploadImage', formdata, {
headers: {
'Content-Type': 'multipart/form-data'
}}).then((resp) => {
if (resp.status === 200) {
console.log(resp.data)
this.addForm.pictures = resp.data;
_this.$message({type: 'success', message: '图片上传成功!'})
}
}).catch(() => {
this.$message({type: 'info', message: '图片太大或格式有误,上传失败,请重新上传!'})
})
}
}
实体类
package com.bishe.springboot.bean;
public class InStock {
private int id;
private String itemname;
private int numbers;
private int fromwho;
private String worker;
private int state;
private String unit;
private String pictures;
public InStock() {
}
public InStock(int id, String itemname, int numbers, int fromwho, String worker, int state, String unit, String pictures) {
this.id = id;
this.itemname = itemname;
this.numbers = numbers;
this.fromwho = fromwho;
this.worker = worker;
this.state = state;
this.unit = unit;
this.pictures = pictures;
}
public int getId() {
return id;
}
public String getItemname() {
return itemname;
}
public int getNumbers() {
return numbers;
}
public int getFromwho() {
return fromwho;
}
public String getWorker() {
return worker;
}
public int getState() {
return state;
}
public String getUnit() {
return unit;
}
public String getPictures() {
return pictures;
}
public void setId(int id) {
this.id = id;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public void setNumbers(int numbers) {
this.numbers = numbers;
}
public void setFromwho(int fromwho) {
this.fromwho = fromwho;
}
public void setWorker(String worker) {
this.worker = worker;
}
public void setState(int state) {this.state = state;}
public void setUnit(String unit) {
this.unit = unit;
}
public void setPictures(String pictures) {
this.pictures = pictures;
}
@Override
public String toString() {
return "InStock{" +
"id=" + id +
", itemname='" + itemname + '\'' +
", numbers=" + numbers +
", fromwho=" + fromwho +
", worker='" + worker + '\'' +
", state=" + state +
", unit='" + unit + '\'' +
", pictures='" + pictures + '\'' +
'}';
}
}
dao文件
public int addIn(InStock inStock);
mapper文件
<insert id="addIn">
INSERT INTO instock
(itemname,numbers,fromwho,worker,state,unit,pictures)
VALUE
(#{itemname},#{numbers},#{fromwho},#{worker},#{state},#{unit},#{pictures})
</insert>
controller文件
@RequestMapping("/addIn2")
public String addIn2(@RequestBody InStock inStock){
inStock.setState(0);
inStock.setFromwho(2);
int i = inStockDao.addIn(inStock);
return i > 0 ? "success":"error";
}
问题可能出在点击“立即捐赠”按钮时,图片上传和表单提交的顺序上。在当前实现中,图片上传是在表单验证通过后进行的,这导致了点击一次按钮时,图片上传和路径保存无法在同一步操作中完成。当您点击第二次按钮时,第一次上传的图片路径已经存在,所以能够保存到数据库。
为了解决这个问题,可以尝试以下修改:
①在addIn方法中,先执行图片上传操作,然后再进行表单验证。
async addIn() {
// 先执行图片上传
await this.$refs.upload.submit();
// 进行表单验证和提交
this.$refs.addFormRef.validate(async valid => {
if (!valid) return;
const {data: res} = await this.$http.post("addIn2", this.addForm);
if (res != "success") {
return this.$message.error("捐赠失败~");
}
this.$message.success("捐赠成功~");
console.log(this.addForm);
this.addDialogVisible = false;
});
},
②修改upload方法,使其返回一个Promise,以便在addIn方法中等待图片上传完成。
upload (file) {
const _this = this
let formdata = new FormData()
// 返回一个Promise,用于等待图片上传完成
return new Promise((resolve, reject) => {
// 上传图片并返回路径
formdata.append('pictures', file.file)
_this.$http.post('/api/uploadImage', formdata, {
headers: {
'Content-Type': 'multipart/form-data'
}}).then((resp) => {
if (resp.status === 200) {
console.log(resp.data)
this.addForm.pictures = resp.data;
_this.$message({type: 'success', message: '图片上传成功!'})
resolve(); // 上传成功,调用resolve
}
}).catch(() => {
this.$message({type: 'info', message: '图片太大或格式有误,上传失败,请重新上传!'})
reject(); // 上传失败,调用reject
})
});
}
不知道你这个问题是否已经解决, 如果还没有解决的话: