`
周一Monday
  • 浏览: 342611 次
  • 来自: 北京
社区版块
存档分类
最新评论

SpringMVC文件上传异常(CommonsMultipartFile异常)

阅读更多

异常如下:

Failed to convert property value of type org.springframework.web.multipart.commons.CommonsMultipartFile to required type byte[] for property photo; 
nested exception is java.lang.IllegalArgumentException: 
Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile]
to required type [byte] for property photo[0]: PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] 
returned inappropriate value of type [org.springframework.web.multipart.commons.CommonsMultipartFile]

 

起初我的代码是这么写的:

 

<input type="file" name="photo"/>

 

public class User {

	@Lob
	private byte[] photo;
	
	//其他的字段略去

}

 

	@RequestMapping("/store.html")
	public String store(@ModelAttribute("user") User user,  HttpServletRequest request, @RequestParam("photo") MultipartFile file)
			throws Exception {
		// 文件上传
		if (!file.isEmpty()) {
			// 存入到服务器
			String path = request.getSession().getServletContext().getRealPath(File.separator) + "upload" + File.separator
					+ file.getOriginalFilename();
			file.transferTo(new File(path));
		}
		userService.save(user);
		return "redirect:list.html";
	}

 

当初的想法是这样:使用SpringMVC提供的文件上传,用

<form:form action="${ctx }/user/store.html" modelAttribute="user" enctype="multipart/form-data">

 

@ModelAttribute("user") User user

绑定表单参数,然后一个save()方法就插入一个对象,包括photo字段。

但是这样是行不通的。表单的字段photo,与User的photo看似对应,但是MultipartFile却无法解析。

 

所以这个“理想”的办法行不通。

 

所以做了一个“折中的方法”。(可能不是最佳方案,提供一个参考)

<input type="file" name="file"/>

 

注意:这个字段名不是实体类的属性名

 

	@RequestMapping("/store.html")
	public String store(@ModelAttribute("user") User user, HttpServletRequest request, @RequestParam("file






") MultipartFile file)
			throws Exception {
		// 文件上传
		if (!file.isEmpty()) {
			// 插入到数据库
			user.setPhoto(file.getBytes());

			// 存入到服务器
			String path = request.getSession().getServletContext().getRealPath(File.separator) + "upload" + File.separator
					+ file.getOriginalFilename();

			file.transferTo(new File(path));
		}
		user.setRegisteredTime(new Date());
		userService.save(user);
		return "redirect:list.html";
	}

 

 

想法就是:表单的文件字段名与实体类的字段名不一致,然后手动赋值。

 

说明:当初的想法就是文件上传到服务器,并且存到数据库(真正的不一定这么做)。

 

我总觉得这不是最好的办法。

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics