我试图将图像存储在我的数据库中,但是我收到了这个错误。我哪里错了?
JSP
<form:form class="form-horizontal" method="post"
modelAttribute="bookForm" action="${bookActionUrl}" enctype="multipart/form-data">
<spring:bind path="image">
<div class="form-group ${status.error ? 'has-error' : ''}">
<label class="col-sm-2 control-label"><th><spring:message
code="label.image" /></th></label>
<div class="col-sm-10">
<form:label for="image" path="image">Image</form:label>
<form:input path="image" type="file" />
<form:errors path="image" class="control-label" />
</div>
</div>
</spring:bind>
</form:form>
控制器
public String saveBook(@ModelAttribute("bookForm") @Validated Book book, BindingResult result, Model model, @RequestParam CommonsMultipartFile[] image,
final RedirectAttributes redirectAttributes) throws IOException {
for (CommonsMultipartFile aFile : image) {
System.out.println("Saving file: " + aFile.getOriginalFilename());
book.setImage_name(aFile.getOriginalFilename());
book.setImage(aFile.getBytes());
System.out.println("Added");
}
if (result.hasErrors()) {
model.addAttribute("genreList", populateDefaultModel(model));
return "booksView/bookform";
} else {
redirectAttributes.addFlashAttribute("css", "success");
if (book.isNew()) {
// System.out.println(book.getId());
redirectAttributes.addFlashAttribute("msg", "book added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "book updated successfully!");
}
bookService.saveOrUpdate(book);
// POST/REDIRECT/GET
return "redirect:/motsach/"; // + book.getId();
}
}
multipartResolver
@Bean(name = "multipartResolver")
public CommonsMultipartResolver getCommonsMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(20971520); // 20MB
multipartResolver.setMaxInMemorySize(1048576); // 1MB
return multipartResolver;
}
DAO实施
public void save(Book book) {
// TODO Auto-generated method stub
KeyHolder keyHolder = new GeneratedKeyHolder();
String sql = "INSERT INTO Books(TENSACH, TACGIA, NHANXET, TINHTRANG, THELOAI, IMAGE, IMAGE_NAME) "
+ "VALUES ( :tensach, :tacgia, :nhanxet, :tinhtrang, :theloai, :image, :image_name)";
namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(book), keyHolder);
book.setId(keyHolder.getKey().intValue());
}
模型
Integer book_ID;
String tensach;
String tacgia;
String nhanxet;
String tinhtrang;
List<String> theloai;
byte[] image;
String image_name;
String data;
错误:
无法将org.springframework.web.multipart.commons.CommonsMultipartFile类型的属性值转换为属性图像所需的类型byte []; 嵌套异常是java.lang.IllegalArgumentException: 无法将org.springframework.web.multipart.commons.CommonsMultipartFile类型的值转换为属性image [0]所需的类型字节:PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor]返回类型为org.springframework.web的不适当值。 multipart.commons.CommonsMultipartFile`
答案 0 :(得分:0)
谢谢大家,我已经明白了。一切都很好,但那些检查代码会导致错误。我只需删除它们就完成了!
if (result.hasErrors()) {
model.addAttribute("genreList", populateDefaultModel(model));
return "booksView/bookform";
} else {