示例:导入相关数据(Excel文件),相关的文件数据编辑好。
XML文件配置
再spring的xml文件中配置要上传文件的大小
<!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760" />
</bean>
Jsp界面配置
<div>
<form id="sourcefile" name="sourcefile" action="" method="post" enctype="multipart/form-data">
<input type="button" value="添 加" onClick="addAirLine()" />
<input style="margin-left: 20px;" id="source_file" name="sourceFile" type="file" value="选择文件" />
<input style="margin-left: 20px;" data-loading-text="请勿重复提交" type="submit" value="上 传" onClick="upPolicy()">
<input style="margin-left: 20px;" type="submit" value="下载模板" onClick="return downloadTemplate();">
</form>
</div>
js文件
function upPolicy() {
document.sourcefile.action = "/login/policy/uploadCSV";
var submitUrl = document.getElementById("sourcefile").attributes["action"].value;
$.ajax({
type: "POST",
url: submitUrl,
data: $('#sourcefile').serialize(),
dataType: "json",
success: function (result) {
var json = JSON.parse(result);
if (json.flag == "0" || json.flag == "1") {
alert(tableJson.success);
return;
}
}
})
}
Controller配置
@RequestMapping(value = "/uploadCSV" ,method = RequestMethod.POST)
@ResponseBody
public String uploadCSV(@RequestParam("sourceFile") MultipartFile sourceFile, HttpServletRequest request,HttpServletResponse response) throws IOException{
//判断文件是否为空
if (sourceFile==null) return null;
//获取文件名
String name=sourceFile.getOriginalFilename();
//进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)
long size =sourceFile.getSize();
if (name==null ||("").equals(name) && size==0) return null;
//批量导入。参数:文件名,文件。
boolean b = batchImport(name,sourceFile);
JSONObject jsonObject=new JSONObject();
if(b){
jsonObject.put("flag",0);
jsonObject.put("success","批量导入EXCEL成功!");
}else{
jsonObject.put("flag",1);
jsonObject.put("success","批量导入EXCEL失败!");
}
return jsonObject.toString();
}
分层没有那么的详细,再Controller中做的处理
public boolean batchImport(String name,MultipartFile file){
boolean b =