首先我的html表单页面是这样的
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../index2Files/css/Home.css" rel="stylesheet" type="text/css">
<title>addDocument</title>
</head>
<body>
<div style='overflow:hidden;margin-left:10px;padding-top:10px'>
<form action="/exam/upload" method="post" enctype="multipart/form-data" id="uploadFile" target="test">
<input id="filepath" type="text" length="30" class="input-bg" readonly="readonly" style="font-size:20px;color:#00d2ff"/>
<input type="file" name="file" class="file1" id="file" style="display:none;" size="28" οnchange="getuploadFile()" />
<input id="scan" type="button" class="zhixing-bt" value="浏览" οnclick="file1()"/>
<input id="import" type="submit" class="zhixing-bt" value="导入"/>
</form>
</div>
<iframe name="test"></iframe>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../js/jquery.form.js"></script>
</body>
</html>
里面的js函数可以先不用管它,不涉及到文件提交然后是后台接收
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import main.java.bean.ExamQuestion;
import main.java.service.ExamService;
import main.java.util.BeanUtil;
import main.java.util.Util;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping(value="/exam")
public class ExamController {
private ExamService examService = (ExamService) BeanUtil.getBeanByName("examService");
@RequestMapping(value="/upload" , method = RequestMethod.POST)
@ResponseBody
public JSONObject upload(@RequestParam("file")MultipartFile[] files , HttpServletRequest request, HttpServletResponse response){
File orgFile = null ;
for(MultipartFile myfile : files){
if(myfile.isEmpty()){
System.out.println("文件未上传");
}else{
System.out.println("文件长度: " + myfile.getSize());
System.out.println("文件类型: " + myfile.getContentType());
System.out.println("文件名称: " + myfile.getName());
System.out.println("文件原名: " + myfile.getOriginalFilename());
System.out.println("========================================");
//如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
InputStream in = null ;
FileOutputStream out = null ;
try{
in = myfile.getInputStream();
byte[] buffer = new byte[1024] ;
int length = 0 ;
File filedir = new File(realPath);
if(!filedir.exists()){
filedir.mkdirs();
}
orgFile = new File(realPath+"\\"+myfile.getOriginalFilename()) ;
out = new FileOutputStream(orgFile);
while((length = in.read(buffer)) != -1){
out.write(buffer, 0, length);
}
out.flush();
}
catch(Exception e ){
e.printStackTrace();
}
finally{
if(in!= null ){
try {
in.close() ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(out!= null ){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
JSONObject result = new JSONObject();
result.put("success", "false") ;
List<ExamQuestion> questionList = new ArrayList<ExamQuestion>();
if( orgFile != null && orgFile.exists()){}
if(questionList != null && questionList.size() > 0 ){
examService.addQuestionBatch(questionList);
result.put("success", "true") ;
}
return result ;
}
}
在这基础上,springmvc的配置需要添加如下信息
</bean> <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> <property name="maxUploadSize" value="2000000"/> </bean> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 --> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop> </props> </property> </bean>