说起上传,相信各位都使用过,这里写的是Spring自带的上传方法,Spring 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);
-
- }
- }
- 也可以在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” 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>
Author:
Pale Life
From:
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。