我正在尝试使用 apache commons 上传图像,但在与我的实体绑定时出现异常。
表单对象
<sf:form action="${contextPath}client/saveClient" modelAttribute="client" method="POST"
enctype="multipart/form-data">
<label>Add Logo</label><input type="file" name='logo' /><br/>
</sf:form>
控制器
@RequestMapping("/saveClient")
public ModelAndView addClient(@RequestParam("logo") MultipartFile file, HttpSession request,
@Valid Client client, BindingResult result, Model model) throws IOException {
ModelAndView mvc = new ModelAndView();
if (result.hasErrors()) {
mvc.addObject("client", client);
mvc.setViewName(MANAGECLIENT_PREFIX + "addclient");
return mvc;
} else {
clientService.uploadImage(file, request);
clientRepository.add(client);
model.addAttribute("client", client);
mvc.setViewName(MANAGECLIENT_PREFIX + "saveclient");
return mvc;
}
}
服务
public void uploadImage(MultipartFile file, HttpSession request) throws IOException {
logger.info("Enter upload client logo");
Utilities utilities = new Utilities();
if (!file.isEmpty()) {
String fileName = (utilities.getUniqueId() + file.getOriginalFilename());
System.out.println("Image name: {" + fileName + "}");
String contextPath = request.getServletContext().getRealPath("/");
String filePath = contextPath + "\\WEB-INF\\clientlogo\\" + fileName;
String validFileFormat = utilities.validFileFormat(fileName);
if (!validFileFormat.isEmpty()) {
BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
File destination = new File(filePath);
ImageIO.write(src, validFileFormat, destination);
client.setLogo(fileName);
}
}
}
实体
@Column(name = "logo")
private String logo;
例外
Field error in object 'client' on field 'logo': rejected value [org.springframework.web.multipart.commons.CommonsMultipa
rtFile@58d51629]; codes [typeMismatch.client.logo,typeMismatch.logo,typeMismatch.java.lang.String,typeMismatch]; argumen
ts [org.springframework.context.support.DefaultMessageSourceResolvable: codes [client.logo,logo]; arguments []; default
message [logo]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.commons.Co
mmonsMultipartFile' to required type 'java.lang.String' for property 'logo'; nested exception is java.lang.IllegalStateE
xception: Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type
[java.lang.String] for property 'logo': no matching editors or conversion strategy found]}]
我正在尝试将图像名称存储在数据库中,并将图像存储在应用程序目录中。我应该如何解决这种类型转换。