转:http://yanglei008.iteye.com/blog/246920
...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); // to do } }
也可以在Spring配置文件中配置
Xml代码
<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>
时间: 2024-10-06 14:42:46