效果
前端代码
html:
<el-form-item label="上传图片">
<el-upload
class="upload-demo"
:limit="4"
action="https://jsonplaceholder.typicode.com/posts/"
:on-change="handleChange"
:on-remove="handleRemove"
:on-exceed="handleExceed"
:file-list="fileList"
:http-request="getFile"
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过4张</div>
</el-upload>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">立即发布</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
js:
data() {
return {
file: {},
fileList: []
}
}
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
if (this.fileList=="") {
this.$message({
type: 'info',
message: '上传照片不能为空'
});
return false;
}
var id=[[${session.loginUser.id}]]
this.ruleForm.userId=id;
const formData = new FormData()
this.fileList.forEach((file) => {
formData.append('filename', file.raw)
})
const config = { headers: { 'Content-Type': 'multipart/form-data' }}
//先上传图片,上传后返回图片地址
axios.post('product/updateProductImg', formData,config).then((resp)=>{
if (resp.data.success) {
//获取图片地址
this.ruleForm.files=resp.data.data;
//将图片地址插入到数据库
axios.post('product/addProduct',this.ruleForm).then((resp)=>{
if (resp.data.success) {
this.$message({
type: 'success',
message: '发布成功!'
});
this.resetForm(formName)
}
})
}
})
} else {
this.$message({
type: 'error',
message: '系统出错'
});
return false;
}
});
},
resetForm(formName) {
this.fileList=[];
this.$refs[formName].resetFields();
},
handleChange(file, fileList) {
this.fileList = fileList.slice(-4);
},
handleExceed(files, fileList) {
this.$message.warning(`超出上传限制`);
},
handleRemove(file, fileList) {
this.fileList = fileList;
},
getFile(item) {
this.file = item.file
},
后端controller代码
@PostMapping("/updateProductImg")
@ApiOperation(value = "上传商品图片", produces = MediaType.APPLICATION_JSON_VALUE)
public ResBody updateUserImg(@RequestParam("filename") List<MultipartFile> files) throws Exception{
//图片保存路径
String filePath= "G:\\schoolshop\\src\\main\\resources\\static\\img\\product";
List<String> fileName=new ArrayList<>();
//获取原始图片的拓展名
for (MultipartFile file: files) {
String originalFilename = file.getOriginalFilename();
//新的文件名字
String newFileName = UUID.randomUUID() + originalFilename;
//封装上传文件位置的全路径
File targetFile = new File(filePath, newFileName);
//把本地文件上传到封装上传文件位置的全路径
file.transferTo(targetFile);
fileName.add(newFileName);
}
return new ResBody(fileName);
}
然后将返回的图片地址插入到数据库即可