可以在controller(spring mvc) 或者 action (struts mvc)
中直接使用CommonsMultipartResolver
...Controller...{
//创建一个通用的多部分解析器.
CommonsMultipartResolver commonsMultipartResolver = new
CommonsMultipartResolver(request.getSession().getServletContext());
//设置编码
commonsMultipartResolver.setDefaultEncoding(”utf-8″);
//判断 request 是否有文件上传,即多部分请求...
if (commonsMultipartResolver.isMultipart(request))
{
//转换成多部分request
MultipartHttpServletRequest multipartRequest =
commonsMultipartResolver.resolveMultipart(request);
// file 是指 文件上传标签的 name=值
// 根据 name 获取上传的文件...
MultipartFile file = multipartRequest.getFile("file");
//上传后记录的文件...
File imageFile = new File("fileName");
//上传...
file.transferTo(imageFile);
}
}
...Controller...{
//创建一个通用的多部分解析器.
CommonsMultipartResolver commonsMultipartResolver = new
CommonsMultipartResolver(request.getSession().getServletContext());
//设置编码
commonsMultipartResolver.setDefaultEncoding(”utf-8″);
//判断 request 是否有文件上传,即多部分请求...
if (commonsMultipartResolver.isMultipart(request))
{
//转换成多部分request
MultipartHttpServletRequest multipartRequest =
commonsMultipartResolver.resolveMultipart(request);
// file 是指 文件上传标签的 name=值
// 根据 name 获取上传的文件...
MultipartFile file = multipartRequest.getFile("file");
//上传后记录的文件...
File imageFile = new File("fileName");
//上传...
file.transferTo(imageFile);
}
}
也可以在spring配置文件中配置
<bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”>
<property name=”defaultEncoding” value=”UTF-8″ />
</bean>
<bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”>
<property name=”defaultEncoding” value=”UTF-8″ />
</bean>
jsp code
<form id=”fileUploadForm” method=”post” action=”XXX.do?method=fileUpload” enctype=”multipart/form-data”>
<tr>
<td>File:</td>
<td><input type=”file” name=”file”></td>
</tr>
<tr>
<td><input type=”hidden” name=”fileOwner” value=”1002″/></td>
<td><input type=”submit” value=”submit”></td>
</tr>
</form>
这是通过md5加密方式进行文件上传处理的代码
@RequestMapping(path = { "/add" }, method = RequestMethod.POST)
public String addUser(MultipartFile image, String name, int age, HttpServletRequest request) {
UserDO user = new UserDO();
user.setName(name);
user.setAge(age);
if (!image.isEmpty()) {
String uploadPath = request.getServletContext().getRealPath("/upload");
try {
String imageName = DigestUtils.md5DigestAsHex(image.getBytes());
File file = new File(uploadPath + "/" + imageName + ".png");
image.transferTo(file);
user.setPhoto(imageName);
} catch (IOException e) {
e.printStackTrace();
}
} else {
user.setPhoto("default");
}
service.addUser(user);
return "redirect:/user/list";
}
jsp code
<input type="file" name="image">