java组件commons-fileupload实现文件上传
一、所需要的包:
1、commons-fileupload-1.2.1.jar:
下载地址
http://commons.apache.org/downloads/download_fileupload.cgi
2、commons-io-1.4.jar:
下载地址
http://commons.apache.org/downloads/download_io.cgi
二、注意事项:
form表单里面要加上enctype="multipart/form-data"
三、代码示例
1、jsp代码:
<%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <!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"> <title>upload</title> </head> <body> <formaction="uploadServlet"method="post"enctype="multipart/form-data"> <table> <caption>上传实例</caption> <tr> <td>姓名</td> <td> <inputtype="text"name="name"> </td> </tr> <tr> <td>年龄</td> <td> <inputtype="text"name="age"> </td> </tr> <tr> <td>照片</td> <td> <inputtype="file"name="image"> </td> </tr> <tr> <td></td> <td> <inputtype="submit"value="提交"> </td> </tr> </table> </form> </body> </html>
2、UploadServlet代码
packageservlet; importjava.io.BufferedInputStream; importjava.io.BufferedOutputStream; importjava.io.File; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.Writer; 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.FileUploadException; importorg.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; importorg.apache.commons.fileupload.disk.DiskFileItemFactory; importorg.apache.commons.fileupload.servlet.ServletFileUpload; importorg.apache.commons.fileupload.util.Streams; /** *上传servlet *@authorlisanlai * */ publicclassUploadServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=1L; publicUploadServlet(){ super(); } protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ this.doPost(request,response); } @SuppressWarnings("unchecked") protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ response.setContentType("text/html"); //设置字符编码为UTF-8,这样支持汉字显示 response.setCharacterEncoding("UTF-8"); Writero=response.getWriter(); /** *首先判断form的enctype是不是multipart/form-data *同时也判断了form的提交方式是不是post *方法:isMultipartContent(request) */ if(ServletFileUpload.isMultipartContent(request)){ request.setCharacterEncoding("utf-8"); //实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactoryfactory=newDiskFileItemFactory(); //设置文件存放的临时文件夹,这个文件夹要真实存在 FilefileDir=newFile("../webapps/fileupload/tmp/"); if(fileDir.isDirectory()&&fileDir.exists()==false){ fileDir.mkdir(); } factory.setRepository(fileDir); //设置最大占用的内存 factory.setSizeThreshold(1024000); //创建ServletFileUpload对象 ServletFileUploadsfu=newServletFileUpload(factory); sfu.setHeaderEncoding("utf-8"); //设置单个文件最大值byte sfu.setFileSizeMax(102400000); //所有上传文件的总和最大值byte sfu.setSizeMax(204800000); List<FileItem>items=null; try{ items=sfu.parseRequest(request); }catch(SizeLimitExceededExceptione){ System.out.println("文件大小超过了最大值"); }catch(FileUploadExceptione){ e.printStackTrace(); } //取得items的迭代器 Iterator<FileItem>iter=items==null?null:items.iterator(); //图片上传后存放的路径目录 Fileimages=newFile("D:/upload/images/"); if(images.exists()==false){ images.mkdirs(); } //迭代items while(iter!=null&&iter.hasNext()){ FileItemitem=(FileItem)iter.next(); //如果传过来的是普通的表单域 if(item.isFormField()){ System.out.print("普通的表单域:"); System.out.print(newString(item.getFieldName())+""); System.out.println(newString(item.getString("UTF-8"))); } //文件域 elseif(!item.isFormField()){ System.out.println("源图片:"+item.getName()); StringfileName=item.getName().substring(item.getName().lastIndexOf("\\")); BufferedInputStreamin=newBufferedInputStream(item.getInputStream()); //文件存储在D:/upload/images目录下,这个目录也得存在 BufferedOutputStreamout=newBufferedOutputStream( newFileOutputStream(newFile(images.getAbsolutePath()+fileName))); Streams.copy(in,out,true); o.write("文件上传成功"); } } }else{ System.out.println("表单的enctype类型错误"); } } }
3、web.xml
<?xmlversion="1.0"encoding="UTF-8"?> <web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID"version="2.5"> <display-name>UploadTest</display-name> <welcome-file-list> <welcome-file>upload.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/uploadServlet</url-pattern> </servlet-mapping> </web-app>
本文已被整理到了《Java上传操作技巧汇总》,欢迎大家学习阅读。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。