我正在从jsp保存图像文件并在控制器中重命名
问题是同一段代码在控制器的一个部分工作而不在控制器的另一部分工作
这里是jsp代码,在两种情况下都是相同的: -
<div class="form-group ">
<label for="photo">Photo:</label>
<form:input type="file" class="filestyle" path="studentPhoto"
id="studentPhoto" placeholder="Upload Photo"
required="required" />
</div>
以下是控制器按预期工作的部分: -
@RequestMapping(value = "/student", params = "add", method = RequestMethod.POST)
public String postAddStudent(@ModelAttribute @Valid Student student,
BindingResult result, Model model) throws IOException {
if (result.hasErrors()) {
System.out.println(result.getAllErrors().toString());
model.addAttribute("examination_names", ExaminationName.values());
ArrayList<Role> roles = new ArrayList<Role>();
roles.add(Role.STUDENT);
model.addAttribute("roles", roles);
return "student/add";
} else {
System.out.println("Inside postAddStudent");
System.out.println(student);
student = studentService.save(student);
String PROFILE_UPLOAD_LOCATION = servletContext.getRealPath("/")
+ File.separator + "resources" + File.separator
+ "student_images" + File.separator;
BufferedImage photo = ImageIO.read(new ByteArrayInputStream(student
.getStudentPhoto().getBytes()));
File destination = new File(PROFILE_UPLOAD_LOCATION
+ student.getId() + "_photo" + ".jpg");
ImageIO.write(photo, "jpg", destination);
return "redirect:student?id=" + student.getId();
}
}
以下是控制器无法正常工作的部分,并说错误: -
Failed to convert property value of type java.lang.String to required type org.springframework.web.multipart.MultipartFile for property studentPhoto; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.MultipartFile] for property studentPhoto: no matching editors or conversion strategy found
ControllerCode
@RequestMapping(value = "/examForm", params = "edit", method = RequestMethod.POST)
public String postEditExamForm(@ModelAttribute @Valid Student student,
BindingResult result, Model model) throws IOException {
String PROFILE_UPLOAD_LOCATION = servletContext.getRealPath("/")
+ File.separator + "resources" + File.separator
+ "student_images" + File.separator;
if (result.hasErrors()) {
model.addAttribute("flags", Flag.values());
return "examForm/edit";
} else {
Student updatedStudent = studentService.findOne(student.getId());
updatedStudent.setDisqualifiedDescription(student
.getDisqualifiedDescription());
student = studentService.update(updatedStudent);
BufferedImage photo = ImageIO.read(new ByteArrayInputStream(student
.getStudentPhoto().getBytes()));
File destination = new File(PROFILE_UPLOAD_LOCATION
+ student.getId() + "_photo" + ".jpg");
ImageIO.write(photo, "jpg", destination);
return "redirect:examForm?id=" + updatedStudent.getId();
}
}
答案 0 :(得分:12)
您的enctype="multipart/form-data"
代码中缺少<form:form...>
。
由于您的表单没有enctype="multipart/form-data"
春天将<form:input type="file"..
作为String
并且在无法将String
转换为MultipartFile
时抛出错误studentPhoto
类中MultipartFile
类型的Student
。
这里是完整的source code。