第一步
前端写html的代码
*上传图片
//完成增加方法
add:function (){
let params = new FormData();
params.append('id',this.id);
params.append('saleId',this.saleId);
params.append('saleName',this.saleName);
params.append('sex',this.sex);
let files = $("#file")[0].files[0];
params.append('file',files);
let config = {
'Content-Type':false
};
axios.post('/sale/add', params,config)
.then(function (response) {
if (response.status == 200){
console.log(response.data);
//执行重定向
// window.location.href = response.data;
var index = parent.layer.getframeIndex(window.name);
//关闭当前页 关闭小弹窗
parent.layer.close(index);
parent.location.reload(); //刷新父页面
}
})
.catch(function (error) {
// console.log(error.data);//undefined,之前以为这样可以拿到错误信息
// console.log(error.response.data.rentCarTime);//可以拿到后端返回的信息
});
}
后端需要导入的pom依赖
commons-fileupload
commons-fileupload
1.3.1
#文件上传到指定项目目录
upload-path: E:/car-manager/src/main/resources/static/images/
spring:
resources:
static-locations: classpath:/static/,file:${upload-path}
spring.http.multipart.enabled=false
multipart.maxFileSize=5000KB
multipart.maxRequestSize=5000KB
controller
@Value("${upload-path}")
private String uploadPath;
//增
@PostMapping("/add")
@ResponseBody
public String saleAdd(Sale sale, FileAll fileAll) throws IOException {
System.out.println(sale);
System.out.println(fileAll.getFile());
MultipartFile file = fileAll.getFile();
if (!file.isEmpty()){
// 获得图片名字
String filename = file.getOriginalFilename();
// 将完整路径放到一个对象里面
String fileAlls = uploadPath+filename;
System.out.println(uploadPath);
System.out.println(fileAlls);
// 把图片的名字放到sale对象里面保存
sale.setImgPath(filename);
// 保存到数据库
saleService.save(sale);
// 保存到项目的指定文件夹
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(fileAlls));
}
return null;
}



