直接上代码:
JSP页面代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../../css/bootstrapcss/bootstrap.min.css"> <script type="text/javascript" src="../../js/jquery-1.11.3.js"></script> <script type="text/javascript" src="../../js/bootstrapjs/bootstrap.min.js"></script> <title>Insert title here</title> </head> <body> <form action="http://10.10.0.158:8080/newBeginning//ajaxfileupload/upload2.do" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="upfile" multiple="multiple"/> <input type="submit" value="Submit" /> </form> <table> </table> </body> <script type="text/javascript"> </script> </html>
后台Java springMVC代码:(注意,此处除了springMVC的一般jar包外,还需要com.springsource.org.apache.commons.fileupload-1.2.0.jar和com.springsource.org.apache.commons.io-1.4.0.jar)
package com.sxdx.ajaxfileupload.action; import java.io.File; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @Controller @RequestMapping(value="/ajaxfileupload") public class ajaxfileupload { @RequestMapping(value="/upload2.do") public void upload2(HttpServletRequest request,HttpServletResponse response) throws Exception{ System.out.println("dsaf"); //创建一个通用的多部分解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //判断request是否有文件需要上传 if(multipartResolver.isMultipart(request)){ //转换成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; List<MultipartFile> fileList = multiRequest.getFiles("file"); for (MultipartFile mf : fileList) { if(!mf.isEmpty()){ //取得当前上传文件的名称 String myFileName = mf.getOriginalFilename(); //如果名称不为"",说明该文件存在,否则说明文件不存在。 if(myFileName.trim()!=""){ System.out.println(myFileName); //重命名上传后的文件 String filename = "demoupload"+mf.getOriginalFilename(); //定义上传路劲 String path = "E:/"+filename; File localFile = new File(path); mf.transferTo(localFile); } } } //return "/success"; }else{ //return "/error"; } } }
效果截图:
上传到了E盘的文件:
JSP显示页面:
控制台: