图片上传功能
1.Controller层
主要传入一个MultipartFile类型的集合
public String save(MultipartFile file, ImageInfo imageInfo, Model model){
int i ;
try {
i = imageInfoService.insertImage(file, imageInfo);
if (i == 0){
model.addAttribute("msg", "上传失败!");
return "test";
}else {
model.addAttribute("msg", "上传成功!");
return "redirect:/list";
}
} catch (IOException e) {
e.printStackTrace();
}
return "test";
}
2.Service层
public int insertImage(MultipartFile file, ImageInfo imageInfo) throws IOException {
// 保存图片的路径,图片上传成功后,将路径保存到数据库
String filePath = "";
//获取tomcat绝对路径 例:D:\project\IDEAProject\fruits\out\artifacts
URL base = this.getClass().getResource("/");
try {
//截取路径,例:D:\project\IDEAProject\fruits
filePath = new File(base.getFile(), "../../"+"").getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
// 获取原始图片的扩展名
String originalFilename = file.getOriginalFilename();
// 生成文件新的路径,加上相对路径
String newFileName = "\\statics\\img\\services\\" +originalFilename;
// 封装上传文件位置的全路径
File targetFile = new File(filePath, newFileName);
//上传文件
file.transferTo(targetFile);
//保存到实体类
imageInfo.setImageUrl(newFileName);
//插入数据库
return imageInfoDao.insertSelective(imageInfo);
}