接:http://alog2012.iteye.com/admin/blogs/2040214
一、表单上传
1、引入jar:
- apache.commons-fileupload-1.3.jar
- apache.commons.io-2.4.0.jar
2、修改springmvc配置
<!-- id="multipartResolver"必须是multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- maxUploadSize:文件上传的最大值以byte为单位 --> <property name="maxUploadSize" value="1024000"></property> </bean> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,未进入到Controller方法中 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到fill_error.jsp页--> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">fill_error</prop> </props> </property> </bean>
3、view层页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML> <html> <head> <base href="<%=basePath%>"> <title>SpringMVC fileUpload</title> </head> <body> <form action="test/upload1.do" method="post" enctype="multipart/form-data"> 选择文件1:<input type="file" name="files"> <input type="submit" value="上传"> </form> <form action="test/upload2.do" method="post" enctype="multipart/form-data"> 选择文件2:<input type="file" name="files"> <input type="submit" value="上传"> </form> </body> </html>
4、Controller控制器,接收表单文件
/** * 转向file.jsp * */ @RequestMapping("/tofile.do") public String tofile() { return "file"; } /** * 上传文件1 */ @RequestMapping(value = "/upload1.do") public String upload1(HttpServletRequest request) throws Exception { // 第一步转化request MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request; // 获得文件 MultipartFile mfile = rm.getFile("files"); // 获得文件的字节数组 byte[] bfile = mfile.getBytes(); // 获得文件名 String fileName = mfile.getOriginalFilename(); System.out.println("fileName:" + fileName + "size:" + bfile.length); // 保存文件 savaFile(bfile, fileName); return "jsp1/index"; } /** * 上传文件2 */ @RequestMapping(value = "/upload2.do") public String upload2(@RequestParam("files") MultipartFile file) throws Exception { // 获得文件的字节数组 byte[] bfile = file.getBytes(); // 获得文件名 String fileName = file.getOriginalFilename(); System.out.println("fileName:" + fileName + "size:" + bfile.length); // 保存文件 savaFile(bfile, fileName); return "jsp1/index"; } /** * 将bfile写入c:/fileName * * @param bfile * @param fileName * @throws Exception */ private void savaFile(byte[] bfile, String fileName) throws Exception { // 定义文件的输出流 OutputStream out = new FileOutputStream(new File("C:/", fileName)); out.write(bfile); out.flush(); out.close(); }
二、使用ajaxfileupload上传文件
1、view层页面,引入js文件,这儿使用了“ajaxfileupload.js”
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML> <html> <head> <base href="<%=basePath%>"> <title>SpringMVC ajaxFileUpload</title> <script type="text/javascript" src="js/jquery-1.6.2.js"></script> <script type="text/javascript" src="js/ajaxfileupload.js"></script> <script type="text/javascript"> $("#mybutton").click(function(){ upload(); }); //上传源码 function upload() { $("#myupload").click(); } function uploadFile() { var fileName = $("#myupload").val(); $("#msgdiv p:first").before("您选择的文件为:"+fileName); //异步上传文件 ajaxFileUpload(fileName); } function ajaxFileUpload(fileName){ //执行上传文件操作的函数 $.ajaxFileUpload({ //处理文件上传操作的服务器端地址(可以传参数) url:"test/ajaxUpload.do", secureuri:false, //是否启用安全提交,默认为false fileElementId:'myupload', //文件选择框的id属性 dataType:'text', //服务器返回的格式,可以是json或xml等 success:function(data, status){ //服务器响应成功时的处理函数 $("#msgdiv p:first").before(data); }, error:function(data, status, e){ //服务器响应失败时的处理函数 $("#msgdiv p:first").before(e); } }); } </script> </head> <body> </body> <input id="myupload" name="myfiles" type="file" onchange="uploadFile()"/><br> <button id="mybutton">上传</button><br> <div id="msgdiv"><p></p></div> </html>
注意返回结果中带入了<pre>标签,可以使用如下方法去掉<pre>标签
//ajaxFileUpload会对服务器响应回来的text内容加上<pre style="....">text</pre>前后缀 data = data.replace(/<pre.*?>/g, ''); data = data.replace(/<PRE.*?>/g, ''); data = data.replace("<pre>", ''); data = data.replace("<PRE>", ''); data = data.replace("</pre>", ''); data = data.replace("</PRE>", '');
2、Controller控制器,
* 如果只是上传一个文件,则只需MultipartFile类型接收文件,而且无需显式指定@RequestParam注解
* 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,且要指定@RequestParam注解
* 上传多个文件时,前台表单中的所有<input type="file"/>的name属性一致即可,此处为myfiles
* 否则参数里的myfiles无法获取到所有上传的文件
/** * 转向ajaxfile.jsp * */ @RequestMapping("/toajaxfile.do") public String toajaxfile() { return "ajaxfile"; } /** * 这里这里用的是MultipartFile[] myfiles参数,<br> * 所以前台就要用<input type="file" name="myfiles"/> */ @RequestMapping(value = "/ajaxUpload.do") public void ajaxUpload(@RequestParam MultipartFile[] myfiles, HttpServletRequest request, PrintWriter out) throws IOException { /** * 遍历文件,然后处理 */ // 上传文件的原名(即上传前的文件名字) String originalFilename = null; for (MultipartFile myfile : myfiles) { if (myfile.isEmpty()) { out.print("您没有选择文件!"); out.flush(); return; } if (myfile.getSize() > 10485760) { // 10485760=10*1024*1024 out.print("您选择的文件大于了10MB"); out.flush(); return; } // 处理文件 originalFilename = myfile.getOriginalFilename(); try { // 创建接收的新文件,此处还是保存在C盘 File savefile = new File("C:/", originalFilename); // commons.io.FileUtils类,它会自动判断保存位置是否存在,不存在则自动创建 FileUtils.copyInputStreamToFile(myfile.getInputStream(), savefile); // 结果显示回页面 out.print("上传成功!"); out.flush(); } catch (IOException e) { e.printStackTrace(); out.print("文件上传失败" + e.getMessage()); out.flush(); } } }