SpringMVC和jQuery的Ajax简略文件上传示例
SpringMVC和jQuery的Ajax简单文件上传示例
准备工作:
前端引入:1、jquery,我在这里用的是:jquery-1.10.2.min.js
2、ajaxfileupload.js
这里可能会报一些错,所以在json判断那里修改为(网上也有):
末尾那里补充一段:
后台导入spring的jar包,我这里用的是:spring3.0.5
在spring.xml里配置如下:
这里就充分利用框架的便利性帮你都做好了,如果你不在xml里配置这些,那么在controller那里,request.getInputStream()得到的这个流不全是文件流,还包含了其他,需要你自己编码去解析,当然,要解析的话还要知道http相关报文解析知识,所以这里可以充分利用框架的便利性,有兴趣的可以研究下
好了,准备工作做好了,看下前端的具体代码:
js代码为:
后台对应java代码段为:
另外:如果是图片上传的话,你也可以不保存在什么临时目录,可以用base64进行编解码,网上也有很多,简单介绍下:
后台只要这么做:
前台页面只要这么就可以拿到了:
对于json相关不大了解的可以参考我的博文:
http://quarterlifeforjava.iteye.com/blog/2024336
效果和iteye的相似:
准备工作:
前端引入:1、jquery,我在这里用的是:jquery-1.10.2.min.js
2、ajaxfileupload.js
这里可能会报一些错,所以在json判断那里修改为(网上也有):
if ( type == "json" ){ data = r.responseText; var start = data.indexOf(">"); if(start != -1) { var end = data.indexOf("<", start + 1); if(end != -1) { data = data.substring(start + 1, end); } } eval( "data = " + data ); }
末尾那里补充一段:
handleError: function( s, xhr, status, e ) { if ( s.error ) { s.error.call( s.context || window, xhr, status, e ); } if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger ( "ajaxError", [xhr, s, e] ); } }
后台导入spring的jar包,我这里用的是:spring3.0.5
在spring.xml里配置如下:
<!-- 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异常时,跳转到/page/html/errorGolbal.html页面 --> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/page/html/errorGolbal.html</prop> </props> </property> </bean>
这里就充分利用框架的便利性帮你都做好了,如果你不在xml里配置这些,那么在controller那里,request.getInputStream()得到的这个流不全是文件流,还包含了其他,需要你自己编码去解析,当然,要解析的话还要知道http相关报文解析知识,所以这里可以充分利用框架的便利性,有兴趣的可以研究下
好了,准备工作做好了,看下前端的具体代码:
<div id="fileUpLoad" class="manage"> 添附文件 <!-- 自定义 <input type="file"/> --> <input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;com.company.project.services.newCase.fileUpLoad()" hidden="hidden" /> <input type="text" id="txtFoo" readonly="readonly" style="width: 300px" /> <button onclick="btnFile.click()" style="height: 25px;">选择文件</button> </div>
js代码为:
if (!window.com) { window.com = {}; } if (!window.com.company) { window.com.company= {}; } if (!window.com.company.project) { window.com.company.project= {}; } if (!window.com.company.project.services) { window.com.company.project.services = {}; } if (!window.com.company.project.services.newCase) { window.com.company.project.services.newCase = {}; } //生成随机guid数(参考网上) com.company.project.services.newCase.getGuidGenerator = function() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }; //上传文件 com.company.project.services.newCase.fileUpLoad = function(){ var fileName = $("#btnFile").val();//文件名 fileName = fileName.split("\\"); fileName = fileName[fileName.length-1]; var guid = com.company.project.services.newCase.getGuidGenerator();//唯一标识guid var data = {guid:guid}; jQuery.ajaxSettings.traditional = true; $.ajaxFileUpload({ url : '/PROJECT/function.do?method=fileUpLoad', secureuri : false,//安全协议 fileElementId:'btnFile',//id type : 'POST', dataType : 'json', data:data, async : false, error : function(data,status,e) { alert('Operate Failed!'); }, success : function(json) { if (json.resultFlag==false){ alert(json.resultMessage); }else{ alert('文件上传成功!'); var next = $("#fileUpLoad").html(); $("#fileUpLoad").html("<div id='"+guid+"'>"+"文件:"+fileName+" <a href='#' onclick='com.company.project.services.newCase.filedelete("+"\""+guid+"\""+","+"\""+fileName+"\""+")'>删除</a>"+"<br/></div>"); $("#fileUpLoad").append(next); } } }); }; //文件删除 com.company.project.services.newCase.filedelete = function(guid,fileName){ jQuery.ajaxSettings.traditional = true; var data = {guid:guid,fileName:fileName}; $.ajax({ url : '/PROJECT/function.do?method=filedelete', type : 'POST', dataType : 'json', data:data, async : false, error : function() { alert('Operate Failed!'); }, success : function(json) { if (json.resultFlag==false){ alert(json.resultMessage); }else{ alert('删除成功!'); $("#"+guid).remove(); } } }); };
后台对应java代码段为:
@RequestMapping(params = "method=fileUpLoad") //btnFile对应页面的name属性 public void fileUpLoad(@RequestParam MultipartFile[] btnFile, HttpServletRequest request, HttpServletResponse response){ try{ //文件类型:btnFile[0].getContentType() //文件名称:btnFile[0].getName() if(btnFile[0].getSize()>Integer.MAX_VALUE){//文件长度 OutputUtil.jsonArrOutPut(response, JSONArray.fromObject("上传文件过大!")); } InputStream is = btnFile[0].getInputStream();//多文件也适用,我这里就一个文件 //String fileName = request.getParameter("fileName"); String guid = request.getParameter("guid"); byte[] b = new byte[(int)btnFile[0].getSize()]; int read = 0; int i = 0; while((read=is.read())!=-1){ b[i] = (byte) read; i++; } is.close(); OutputStream os = new FileOutputStream(new File("D://"+guid+"."+btnFile[0].getOriginalFilename()));//文件原名,如a.txt os.write(b); os.flush(); os.close(); OutputUtil.jsonOutPut(response, null); }catch (Exception e) { OutputUtil.errorOutPut(response, "系统异常"); } } @RequestMapping(params = "method=filedelete") public void filedelete(HttpServletRequest request, HttpServletResponse response){ try{ String guid = request.getParameter("guid"); String fileName = request.getParameter("fileName"); File file = new File("D://"+guid+"."+fileName); boolean isDeleted = file.delete(); if(!isDeleted){ OutputUtil.errorOutPut(response, "文件删除失败"); } OutputUtil.jsonArrOutPut(response, null); }catch (Exception e) { OutputUtil.errorOutPut(response, "系统异常"); } }
另外:如果是图片上传的话,你也可以不保存在什么临时目录,可以用base64进行编解码,网上也有很多,简单介绍下:
后台只要这么做:
//得到byte数组后 BASE64Encoder base64e = new BASE64Encoder(); JSONArray ja = new JSONArray(); String base64Str = base64e.encode(b); ja.add(base64Str); OutputUtil.jsonArrOutPut(response, JSONArray.fromObject(ja));
前台页面只要这么就可以拿到了:
$("#fileUpLoad") .append("<image src='"+"data:image/gif;base64,"+json.resultMessage[0]+"' >");
对于json相关不大了解的可以参考我的博文:
http://quarterlifeforjava.iteye.com/blog/2024336
效果和iteye的相似: