Apache Commons fileUpload文件上传多个示例分享
本文通过实例来介绍如何使用commons-fileupload.jar,Apache的commons-fileupload.jar可方便的实现文件的上传功能,具体内容如下
将Apache的commons-fileupload.jar放在应用程序的WEB-INF\lib下,即可使用。下面举例介绍如何使用它的文件上传功能。
所使用的fileUpload版本为1.2,环境为Eclipse3.3+MyEclipse6.0。FileUpload是基于CommonsIO的,所以在进入项目前先确定CommonsIO的jar包(本文使用commons-io-1.3.2.jar)在WEB-INF\lib下。
此文作示例工程可在文章最后的附件中下载。
示例1
最简单的例子,通过ServletFileUpload静态类来解析Request,工厂类FileItemFactory会对mulipart类的表单中的所有字段进行处理,不只是file字段。getName()得到文件名,getString()得到表单数据内容,isFormField()可判断是否为普通的表单项。
demo1.html
<html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=GB18030"> <title>Fileupload</title> </head> <body> //必须是multipart的表单数据。 <formname="myform"action="demo1.jsp"method="post" enctype="multipart/form-data"> Yourname:<br> <inputtype="text"name="name"size="15"><br> File:<br> <inputtype="file"name="myfile"><br> <br> <inputtype="submit"name="submit"value="Commit"> </form> </body> </html>
demo1.jsp
<%@pagelanguage="java"contentType="text/html;charset=GB18030" pageEncoding="GB18030"%> <%@pageimport="org.apache.commons.fileupload.*"%> <%@pageimport="org.apache.commons.fileupload.servlet.*"%> <%@pageimport="org.apache.commons.fileupload.disk.*"%> <%@pageimport="java.util.*"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <% booleanisMultipart=ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。 if(isMultipart==true){ FileItemFactoryfactory=newDiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。 ServletFileUploadupload=newServletFileUpload(factory); List<FileItem>items=upload.parseRequest(request); Iterator<FileItem>itr=items.iterator(); while(itr.hasNext()){ FileItemitem=(FileItem)itr.next(); //检查当前项目是普通表单项目还是上传文件。 if(item.isFormField()){//如果是普通表单项目,显示表单内容。 StringfieldName=item.getFieldName(); if(fieldName.equals("name"))//对应demo1.html中type="text"name="name" out.print("thefieldnameis"+item.getString());//显示表单内容。 out.print("<br>"); }else{//如果是上传文件,显示文件名。 out.print("theuploadfilenameis"+item.getName()); out.print("<br>"); } } }else{ out.print("theenctypemustbemultipart/form-data"); } %> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=GB18030"> <title>Fileupload</title> </head> <body> </body> </html>
结果:
thefieldnameisjeff
theuploadfilenameisD:\C语言考试样题\作业题.rar
示例2
上传两个文件到指定的目录。
demo2.html
<html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=GB18030"> <title>Fileupload</title> </head> <body> <formname="myform"action="demo2.jsp"method="post" enctype="multipart/form-data"> File1:<br> <inputtype="file"name="myfile"><br> File2:<br> <inputtype="file"name="myfile"><br> <br> <inputtype="submit"name="submit"value="Commit"> </form> </body> </html>
demo2.jsp
<%@pagelanguage="java"contentType="text/html;charset=GB18030" pageEncoding="GB18030"%> <%@pageimport="org.apache.commons.fileupload.*"%> <%@pageimport="org.apache.commons.fileupload.servlet.*"%> <%@pageimport="org.apache.commons.fileupload.disk.*"%> <%@pageimport="java.util.*"%> <%@pageimport="java.io.*"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <%StringuploadPath="D:\\temp"; booleanisMultipart=ServletFileUpload.isMultipartContent(request); if(isMultipart==true){ try{ FileItemFactoryfactory=newDiskFileItemFactory(); ServletFileUploadupload=newServletFileUpload(factory); List<FileItem>items=upload.parseRequest(request);//得到所有的文件 Iterator<FileItem>itr=items.iterator(); while(itr.hasNext()){//依次处理每个文件 FileItemitem=(FileItem)itr.next(); StringfileName=item.getName();//获得文件名,包括路径 if(fileName!=null){ FilefullFile=newFile(item.getName()); FilesavedFile=newFile(uploadPath,fullFile.getName()); item.write(savedFile); } } out.print("uploadsucceed"); } catch(Exceptione){ e.printStackTrace(); } } else{ out.println("theenctypemustbemultipart/form-data"); } %> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=GB18030"> <title>Fileupload</title> </head> <body> </body> </html>
结果:
uploadsucceed
此时,在"D:\temp"下可以看到你上传的两个文件。
示例3
上传一个文件到指定的目录,并限定文件大小。
demo3.html
<html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=GB18030"> <title>Fileupload</title> </head> <body> <formname="myform"action="demo3.jsp"method="post" enctype="multipart/form-data"> File:<br> <inputtype="file"name="myfile"><br> <br> <inputtype="submit"name="submit"value="Commit"> </form> </body> </html>
demo3.jsp
<%@pagelanguage="java"contentType="text/html;charset=GB18030" pageEncoding="GB18030"%> <%@pageimport="org.apache.commons.fileupload.*"%> <%@pageimport="org.apache.commons.fileupload.servlet.*"%> <%@pageimport="org.apache.commons.fileupload.disk.*"%> <%@pageimport="java.util.*"%> <%@pageimport="java.io.*"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <% FileuploadPath=newFile("D:\\temp");//上传文件目录 if(!uploadPath.exists()){ uploadPath.mkdirs(); } //临时文件目录 FiletempPathFile=newFile("d:\\temp\\buffer\\"); if(!tempPathFile.exists()){ tempPathFile.mkdirs(); } try{ //Createafactoryfordisk-basedfileitems DiskFileItemFactoryfactory=newDiskFileItemFactory(); //Setfactoryconstraints factory.setSizeThreshold(4096);//设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);//设置缓冲区目录 //Createanewfileuploadhandler ServletFileUploadupload=newServletFileUpload(factory); //Setoverallrequestsizeconstraint upload.setSizeMax(4194304);//设置最大文件尺寸,这里是4MB List<FileItem>items=upload.parseRequest(request);//得到所有的文件 Iterator<FileItem>i=items.iterator(); while(i.hasNext()){ FileItemfi=(FileItem)i.next(); StringfileName=fi.getName(); if(fileName!=null){ FilefullFile=newFile(fi.getName()); FilesavedFile=newFile(uploadPath,fullFile .getName()); fi.write(savedFile); } } out.print("uploadsucceed"); }catch(Exceptione){ e.printStackTrace(); } %> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=GB18030"> <title>Fileupload</title> </head> <body> </body> </html>
示例4
利用Servlet来实现文件上传。
Upload.java
packagecom.zj.sample; importjava.io.File; importjava.io.IOException; importjava.util.Iterator; importjava.util.List; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.apache.commons.fileupload.FileItem; importorg.apache.commons.fileupload.disk.DiskFileItemFactory; importorg.apache.commons.fileupload.servlet.ServletFileUpload; @SuppressWarnings("serial") publicclassUploadextendsHttpServlet{ privateStringuploadPath="D:\\temp";//上传文件的目录 privateStringtempPath="d:\\temp\\buffer\\";//临时文件目录 FiletempPathFile; @SuppressWarnings("unchecked") publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsIOException,ServletException{ try{ //Createafactoryfordisk-basedfileitems DiskFileItemFactoryfactory=newDiskFileItemFactory(); //Setfactoryconstraints factory.setSizeThreshold(4096);//设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);//设置缓冲区目录 //Createanewfileuploadhandler ServletFileUploadupload=newServletFileUpload(factory); //Setoverallrequestsizeconstraint upload.setSizeMax(4194304);//设置最大文件尺寸,这里是4MB List<FileItem>items=upload.parseRequest(request);//得到所有的文件 Iterator<FileItem>i=items.iterator(); while(i.hasNext()){ FileItemfi=(FileItem)i.next(); StringfileName=fi.getName(); if(fileName!=null){ FilefullFile=newFile(fi.getName()); FilesavedFile=newFile(uploadPath,fullFile.getName()); fi.write(savedFile); } } System.out.print("uploadsucceed"); }catch(Exceptione){ //可以跳转出错页面 e.printStackTrace(); } } publicvoidinit()throwsServletException{ FileuploadFile=newFile(uploadPath); if(!uploadFile.exists()){ uploadFile.mkdirs(); } FiletempPathFile=newFile(tempPath); if(!tempPathFile.exists()){ tempPathFile.mkdirs(); } } }
demo4.html
<html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=GB18030"> <title>Fileupload</title> </head> <body> //action="fileupload"对应web.xml中<servlet-mapping>中<url-pattern>的设置. <formname="myform"action="fileupload"method="post" enctype="multipart/form-data"> File:<br> <inputtype="file"name="myfile"><br> <br> <inputtype="submit"name="submit"value="Commit"> </form> </body> </html>
web.xml
<servlet> <servlet-name>Upload</servlet-name> <servlet-class>com.zj.sample.Upload</servlet-class> </servlet> <servlet-mapping> <servlet-name>Upload</servlet-name> <url-pattern>/fileupload</url-pattern> </servlet-mapping>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。