上传图片的方法
- 在上传文件的时候需要知道其原理,因为我们的数据库是无法存储数据的,所以我们只能使用地址来找,所以数据库中应该村的是文件路径
- 其次上传图片是属于上传文件的一种方式,所以也要学会上传文件的方法
- 在之后呢也要注意上传图片和对象的关联
1,上传文件
@PostMapping("/file/{id}")
public String fileUpload(@RequestParam(value = "file") MultipartFile file,@PathVariable("id")Integer id) {
//首先判断输入的文件是否为空,如果是空就返回file页面
if (file.isEmpty()) {
System.out.println("文件为空空");
return "file";
}
String fileName = file.getOriginalFilename(); // 文件名
String filePath = "E:\\作业\\book\\src\\main\\resources\\static\\img\\"; // 上传后的路径
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
Book book1 = bookDao.zym_1913040747_queryBookById(id);
book1.setZym_1913040747_bookPath("img/" + fileName);
System.out.println(book1.getZym_1913040747_bookPath());
return "redirect:/books";
}