This article uses examples to introduce how to use commons-fileupload.jar. Apache's commons-fileupload.jar to facilitate the upload function of files. The specific content is as follows
Place Apache's commons-fileupload.jar under WEB-INF/lib in the application and it is ready to use. The following example shows how to use its file upload function.
The fileUpload version used is 1.2 and the environment is Eclipse3.3+MyEclipse6.0. FileUpload is based on Commons IO, so before entering the project, determine the jar package of Commons IO (using commons-io-1.3.2.jar in this article) under WEB-INF/lib.
This article is an example project that can be downloaded in the attachment at the end of the article.
Example 1
The simplest example is to parse the Request through the ServletFileUpload static class. The factory class FileItemFactory will process all fields in the form of the mulipart class, not just file fields. getName() gets the file name, getString() gets the form data content, and isFormField() can determine whether it is an ordinary form item.
demo1.html
<html><head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title></head><body> // Must be multipart form data. <form name="myform" action="demo1.jsp" method="post" enctype="multipart/form-data"> Your name: <br> <input type="text" name="name" size="15"><br> File:<br> <input type="file" name="myfile"><br> <br> <input type="submit" name="submit" value="Commit"> </form></body></html>
demo1.jsp
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%><%@ page import="org.apache.commons.fileupload.*"%><%@ page import="org.apache.commons.fileupload.servlet.*"%><%@ page import="org.apache.commons.fileupload.disk.*"%><%@ page import="java.util.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><% boolean isMultipart = ServletFileUpload.isMultipartContent(request);//Check whether the input request is multipart form data. if (isMultipart == true) { FileItemFactory factory = new DiskFileItemFactory();//Create a DiskFileItemFactory object for the request and parse the request through it. After the parsing is executed, all form items are saved in a List. ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); //Check whether the current project is a normal form project or an upload file. if (item.isFormField()) {//If it is a normal form item, display the form content. String fieldName = item.getFieldName(); if (fieldName.equals("name")) //Response to type="text" name="name" out.print("the field name is" + item.getString());//Show form contents. out.print("<br>"); } else {//If it is uploading a file, display the file name. out.print("the upload file name is" + item.getName()); out.print("<br>"); } } } else { out.print("the enctype must be multipart/form-data"); }%><html><head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title></head><body></body></html> result:
the field name isjeff
the upload file name isD:/C language test sample/homework questions.rar
Example 2
Upload two files to the specified directory.
demo2.html
<html><head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title></head><body> <form name="myform" action="demo2.jsp" method="post" enctype="multipart/form-data"> File1:<br> <input type="file" name="myfile"><br> File2:<br> <input type="file" name="myfile"><br> <br> <input type="submit" name="submit" value="Commit"> </form></body></html>
demo2.jsp
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%><%@ page import="org.apache.commons.fileupload.*"%><%@ page import="org.apache.commons.fileupload.servlet.*"%><%@ page import="org.apache.commons.fileupload.disk.*"%><%@ page import="java.util.*"%><%@ page import="java.io.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><%String uploadPath="D://temp"; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart==true){ try{ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request);//Get all files Iterator<FileItem> itr = items.iterator(); while(itr.hasNext()){//Train each file item=(FileItem)itr.next(); String fileName=item.getName();//Get the file name, including the path if(fileName!=null){ File fullFile=new File(item.getName()); File savedFile=new File(uploadPath,fullFile.getName()); item.write(savedFile); } } out.print("upload succeed"); } catch(Exception e){ e.printStackTrace(); } } else{ out.println("the enctype must be multipart/form-data"); }%><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><title>File upload</title></head><body></body></html> result:
upload succeed
At this time, you can see the two files you uploaded under "D:/temp".
Example 3
Upload a file to the specified directory and limit the file size.
demo3.html
<html><head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title></head><body> <form name="myform" action="demo3.jsp" method="post" enctype="multipart/form-data"> File:<br> <input type="file" name="myfile"><br> <br> <input type="submit" name="submit" value="Commit"> </form></body></html>
demo3.jsp
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%><%@ page import="org.apache.commons.fileupload.*"%><%@ page import="org.apache.commons.fileupload.servlet.*"%><%@ page import="org.apache.commons.fileupload.disk.*"%><%@ page import="java.util.*"%><%@ page import="java.io.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><% File uploadPath = new File("D://temp");//Upload file directory if (!uploadPath.exists()) { uploadPath.mkdirs(); } // Temporary file directory File tempPathFile = new File("d://temp//buffer//"); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(4096); // Set buffer size, here is 4kb factory.setRepository(tempPathFile); // Set buffer directory// Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(4194304); // Set maximum file size, here is 4MB List<FileItem> items = upload.parseRequest(request);//Get all files Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile .getName()); fi.write(savedFile); } } out.print("upload succeed"); } catch (Exception e) { e.printStackTrace(); }%><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><title>File upload</title></head><body></body></html> Example 4
Use Servlet to implement file upload.
Upload.java
package com.zj.sample; import java.io.File;import java.io.IOException;import java.util.Iterator;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload; @SuppressWarnings("serial")public class Upload extends HttpServlet { private String uploadPath = "D://temp"; // directory for uploading files private String tempPath = "d://temp//buffer//"; // temporary file directory File tempPathFile; @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(4096); // Set buffer size, here is 4kb factory.setRepository(tempPathFile); // Set buffer directory// Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(4194304); // Set maximum file size, here is 4MB List<FileItem> items = upload.parseRequest(request);// Get all files Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile.getName()); fi.write(savedFile); } } System.out.print("upload successed"); } catch (Exception e) { // The error page can be jumped e.printStackTrace(); } } public void init() throws ServletException { File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdirs(); } File tempPathFile = new File(tempPath); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } }} demo4.html
<html><head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title></head><body>// action="fileupload" corresponds to the setting of <url-pattern> in <servlet-mapping> in web.xml. <form name="myform" action="fileupload" method="post" enctype="multipart/form-data"> File:<br> <input type="file" name="myfile"><br> <br> <input type="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>
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.