springMVC结合AjaxForm上传文件
最近在项目中需要上传文件文件,之前一直都是form提交的,尝试了一下AjaxForm,感觉还比较好用,写篇随笔mark下,供以后使用。
准备工作:
下载jquery-form.js
相关jar:
commons-fileupload-1.1.1.jar
commons-io-1.3.2.jar
在spring-servlet.xml进行multipartResolver配置:
<beanid="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <propertyname="defaultEncoding"value="utf-8"/> <propertyname="maxUploadSize"value="10485760000"/> <propertyname="maxInMemorySize"value="40960"/> </bean>
这个是必须的,否则不好用。
页面:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> <%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"session="false"%> <html> <!-- -Author(s):xieshuang -Date:2016-06-2013:46:20 -Description: --> <head> <title>Title</title> <metahttp-equiv="content-type"content="text/html;charset=UTF-8"/> <scriptsrc="<%=request.getContextPath()%>/common/nui/nui.js"type="text/javascript"></script> <scriptsrc="<%=request.getContextPath()%>/common/nui/jquery/jquery-form.js"type="text/javascript"></script> <scripttype="text/javascript"src="<%=request.getContextPath()%>/page4nui/master/projecttype/js/projecttype_import.js"></script> <scripttype="text/javascript"> varcontextPath="<%=request.getContextPath()%>"; </script> </head> <body> <divid="test"class="nui-fit"style="padding-top:5px;min-width:300px;min-height:180px;"> <formid="fileUpload"method="post"enctype="multipart/form-data"> <divid="dataImport"style="width:100%;overflow:hidden;"> <tablestyle="width:100%;table-layout:fixed;"class="nui-form-table"> <tr> <thalign="right"style="width:25%">选择文件:</th> <td> <inputid="uploadFile"type="file"name="file"style="width:90%;"><fontstyle="color:red;width:5%;">*</font> </td> </tr> </table> </div> <divstyle="width:100%;padding-top:10px;"align="center"> <inputstyle="width:60px;"iconCls="icon-ok"value="确定"type="submit"/> <spanstyle="display:inline-block;width:25px;"></span> <aclass="nui-button"iconCls="icon-cancel"style="width:60px;"onclick="cancel">取消</a> </div> </form> </div> </body> </html>
核心js:
varmsg; $(function(){ nui.parse(); //ajax配置 varoptions={ url:contextPath+"/webapp/cfProjectType/importExcel", beforeSubmit:showRequest,//提交前处理 success:showResponse,//处理完成 resetForm:true, dataType:'json' }; $('#fileUpload').submit(function(){//注意 $(this).ajaxSubmit(options); returnfalse;//防止dialog自动关闭 }); }) //执行成功回调函数 functionshowResponse(e){ nui.hideMessageBox(msg); if(e.importFlag==true){ CloseWindow("ok"); }else{ //对错误的一些处理 } } //提交前的一些校验 functionshowRequest(formData,jqForm,options){ if(formData[0].value==""||formData[0].value==null){ nui.alert("请选择文件"); returnfalse; } varfileName=$("#uploadFile").val().split("\\").pop(); varstrs=newArray();//定义一数组 strs=fileName.split('.'); varsuffix=strs[strs.length-1]; if(suffix!='xls'&&suffix!='xlsx'){ nui.alert("请选择excel文件!"); returnfalse; } msg=nui.loading("Loading","Pleasewaiting"); }
java代码:
@SuppressWarnings("unchecked") @RequestMapping("/webapp/cfProjectType/importExcel") @ResponseBody publicMap<String,Object>importExcel(@RequestParam("file")MultipartFile[]files,HttpServletRequestrequest) throwsThrowable{ //longstarttiem=System.currentTimeMillis(); InputStreamfis; fis=null; FilefileIn=null; try{ for(MultipartFilemyfile:files){ if(!myfile.isEmpty()){ StringrealPath=request.getSession().getServletContext().getRealPath("/export"); fileIn=newFile(realPath); //判断上传文件的保存目录是否存在 if(!fileIn.exists()&&!fileIn.isDirectory()){ //创建目录 fileIn.mkdirs(路径); } //将上传的文件复制到文件夹下 myfile.transferTo(newFile(路径+文件名)); } } }
这里我之前用过另外一个方法FileUtils.copyInputStreamToFile(InputStreamarg0,Filearg1)同样能将文件保存到路径下面
更多精彩内容请参考专题《ajax上传技术汇总》,《javascript文件上传操作汇总》和《jQuery上传操作汇总》进行学习。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。