基于jsp的AJAX多文件上传的实例
最近的项目开发中,遇到了一个多文件上传的问题,即在不刷新页面的情况下,上传多个文件至服务器。现总结分享如下:
本文主要采用了基于jsp的ajax,jquery,servlet等技术。
1.upload.jsp
点击上传时,调用对应的fileupload函数,通过ajax将文件异步传送到servlet中处理。注意在文件上载时,所使用的编码类型应当是“multipart/form-data”,它既可以发送文本数据,也支持二进制数据上载。
<%@pagelanguage="java"contentType="text/html;charset=utf-8"pageEncoding="utf-8"%> <% Stringpath=request.getContextPath(); StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"> <basehref="<%=basePath%>"> <title>Inserttitlehere</title> <scripttype="text/javascript"src="js/jquery.js"></script> <scripttype="text/javascript"src="js/ajaxfileupload.js"></script> </head> <scriptlanguage="JavaScript"type="text/javascript"> varbuildph=0; vartypeph=0; varplanph=0; functionfileupload1(){ if($("#locationphoto").val()==""){ alert("上传文件不能为空!"); returnfalse; } varfile=$("#locationphoto").val(); varpos=file.lastIndexOf("\\"); varfileName=file.substring(pos+1);//获得文件名字 $.ajaxFileUpload({ url:"PictureServlet";, contentType:"multipart/form-data;text/xml;charset=utf-8", secureuri:false, cache:false,//防止缓存 fileElementId:'locationphoto', dataType:'text/xml', success:function(data){ document.getElementById("locationspan").innerHTML=fileName; alert(fileName); },error:function(data,status,e){ alert("fail"); } } ); } functionfileupload2(){ if($("#buildingphoto").val()==""){ alert("上传文件不能为空!"); returnfalse; } varfile=$("#buildingphoto").val(); varpos=file.lastIndexOf("\\"); varfileName=file.substring(pos+1); buildph++; $.ajaxFileUpload({ url:"PictureServlet";, contentType:"multipart/form-data;text/xml;charset=utf-8", secureuri:false, cache:false,//防止缓存 fileElementId:'buildingphoto', dataType:'text/xml', success:function(data){ document.getElementById("buildingspan"+buildph).innerHTML=fileName; alert(fileName); },error:function(data,status,e){ alert("fail"); } } ); } functionfileupload3(){ if($("#typePhoto").val()==""){ alert("上传文件不能为空!"); returnfalse; } varfile=$("#typePhoto").val(); varpos=file.lastIndexOf("\\"); varfileName=file.substring(pos+1); typeph++; $.ajaxFileUpload({ url:"PictureServlet";, contentType:"multipart/form-data;text/xml;charset=utf-8", secureuri:false, cache:false,//防止缓存 fileElementId:'typePhoto', dataType:'text/xml', success:function(data){ document.getElementById("typespan"+typeph).innerHTML=fileName; alert(fileName); },error:function(data,status,e){ alert("fail"); } } ); } </script> <body> <formid="form1"name="form1"method="post"action=""> <tablewidth="663"height="316"align="center"> <tr> <tdheight="30"colspan="2">楼盘位置图: <spanid="locationspan"></span> <inputtype="file"name="locationphoto"id="locationphoto"value="this.val()"/> <inputtype="button"name="fileLoad1"id="fileLoad1"value="上传"onClick="fileupload1()"/> </td> </tr> <tr> <tdheight="30"colspan="2">楼盘照片: <spanid="buildingspan1"></span> <spanid="buildingspan2"></span> <spanid="buildingspan3"></span> <spanid="buildingspan4"></span> <inputtype="file"name="buildingphoto"id="buildingphoto"value="this.val()"/> <inputtype="button"name="fileLoad2"id="fileLoad2"value="上传"onClick="fileupload2()"/> </td> </tr> <tr> <tdheight="30"colspan="2">楼盘户型图: <spanid="typespan1"></span> <spanid="typespan2"></span> <spanid="typespan3"></span> <spanid="typespan4"></span> <inputtype="file"name="typePhoto"id="typePhoto"value="this.val()"/> <inputtype="button"name="fileLoad3"id="fileLoad3"value="上传"onClick="fileupload3()"/> </td> </tr> </table> </form> </body> </html>
2.PictureServlet.java
通过该servlet接受jsp上传的数据流,存储到相应路径,并解析出文件名。
packagecom.servlet; importjava.io.BufferedOutputStream; importjava.io.DataOutputStream; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.PrintWriter; importjavax.servlet.ServletException; importjavax.servlet.ServletInputStream; importjavax.servlet.annotation.WebServlet; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importcom.realty.base.action.BuildingAction; /** *ServletimplementationclassPictureServlet */ @WebServlet("/PictureServlet") publicclassPictureServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=1L; /** *@seeHttpServlet#HttpServlet() */ publicPictureServlet(){ super(); //TODOAuto-generatedconstructorstub } /** *@seeHttpServlet#doGet(HttpServletRequestrequest,HttpServletResponseresponse) */ protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ //TODOAuto-generatedmethodstub doPost(request,response); } /** *@seeHttpServlet#doPost(HttpServletRequestrequest,HttpServletResponseresponse) */ protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ //TODOAuto-generatedmethodstub response.setContentType("text/xml");//是xml response.setHeader("Cache-Control","no-cache"); response.setCharacterEncoding("UTF-8"); Stringfilepath="E:/pic/";//文件上传的路径,实际开发中一般用相对路径 Stringfilename=""; Stringname=""; ServletInputStreamin=request.getInputStream(); byte[]buf=newbyte[4048]; intlen=in.readLine(buf,0,buf.length); Stringf=newString(buf,0,len-1); while((len=in.readLine(buf,0,buf.length))!=-1){ filename=newString(buf,0,len,"utf-8");//解决汉字乱码问题 intj=filename.lastIndexOf("\""); ints=filename.indexOf("filename"); name=filename.substring(s+10,j); filename=name;//通过上述处理可以得到上传的文件名 System.out.println("filename="+filename); DataOutputStreamfileStream=newDataOutputStream(newBufferedOutputStream(newFileOutputStream(filepath+filename))); len=in.readLine(buf,0,buf.length); len=in.readLine(buf,0,buf.length); while((len=in.readLine(buf,0,buf.length))!=-1){ Stringtempf=newString(buf,0,len-1); if(tempf.equals(f)||tempf.equals(f+"--")){ break; } else{ fileStream.write(buf,0,len);//写入 } } fileStream.close(); } PrintWriterout=response.getWriter(); Stringresult=filename; out.print(result); out.close(); in.close(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。