-
- ...Controller...{
-
- //创建一个通用的多部分解析器.
-
CommonsMultipartResolver commonsMultipartResolver = new - CommonsMultipartResolver
(request.getSession().getServletContext()); - //设置编码
-
commonsMultipartResolver .setDefaultEncoding(”utf-8″); -
//判断 request 是否有文件上传,即多部分请求... -
if (commonsMultipartResolver .isMultipart(request)) -
{ -
//转换成多部分request -
MultipartHttpServletRequ est multipartRequest = -
commonsMultipartResolver .resolveMultipart(request); -
-
// file 是指 文件上传标签的 name=值 -
// 根据 name 获取上传的文件... -
MultipartFile file = multipartRequest.getFile("file"); -
-
//上传后记录的文件... -
File imageFile = new File( "fileName"); -
//上传... -
file.transferTo(imageFile); -
-
} -
}
- 也可以在Spring的配置文件中添加
- Xml代码
- <bean
id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver ”> - <property
name=”defaultEncoding” value=”UTF-8″ /> - </bean>
- 配置这个后就只需要编写以下代码即可
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile mfile1 = multipartRequest.getFile("file");
- <form
id=”fileUploadForm” do?method=fileUpload”method=”post” action=”XXX. 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>