Apache Commons fileUpload实现文件上传之一
废话不多说了,直奔主题了。
需要两个jar包:
commons-fileupload.jar
CommonsIO的jar包(本文使用commons-io-2.4.jar)
利用Servlet来实现文件上传。
packageweb.servlet; importjava.io.IOException; importjavax.servlet.ServletException; importjavax.servlet.annotation.WebServlet; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjava.io.File; importjava.util.Iterator; importjava.util.List; importorg.apache.commons.fileupload.FileItem; importorg.apache.commons.fileupload.disk.DiskFileItemFactory; importorg.apache.commons.fileupload.servlet.ServletFileUpload; /** *ServletimplementationclassUploadServlet */ @WebServlet("/UploadServlet") publicclassUploadServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=1L; privateStringuploadPath="D:\\temp";//上传文件的目录 privateStringtempPath="d:\\temp\\buffer\\";//临时文件目录 FiletempPathFile; 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(); } } }
jsp
<%@pagelanguage="java"contentType="text/html;charset=ISO--" pageEncoding="utf-"%> <!DOCTYPEhtmlPUBLIC"-//WC//DTDHTML.Transitional//EN""http://www.w.org/TR/html/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=GB"> <title>Fileupload</title> </head> <body> <!--//action="fileupload"对应web.xml中<servlet-mapping>中<url-pattern>的设置.--> <formname="myform"action="UploadServlet"method="post" enctype="multipart/form-data"> File:<br> <inputtype="file"name="myfile"><br> <br> <inputtype="submit"name="submit"value="Commit"> </form> </body> </html>
这样就能简单实现一个文件上传功能了,当然这是最最最基本的,继续研究中。