1. Get the Commons-fileupload component
Download this component in Http://jakarta.apache.org/site/downloads, unzip the file and copy Commoms-fileupload-1.2.jar to the Web-inf/lib directory
2. When using the Commons-fileupload component, another build Commoms-io support is required, which can be found on the http://jakarta.apache.org/site/downloads. Commoms-io.jar copy after download complete
To the Web-inf/lib file directory
You can use this component to complete file uploads through the above configuration:
jsp page for file upload
<%@ page contenttype= "text/html; charset=gb2312 "%>
Servlet that accepts form implementation file uploads
Package servlets;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.Iterator;
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.FileItemFactory;
Import org.apache.commons.fileupload.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUpload extends HttpServlet {public void DoPost (HttpServletRequest request, HttpServletResponse respons E) throws IOException, Servletexception//Judging whether the submitted form Boolean ismultipart for file upload = Servletfileupload.ismultipart
Content (Request);
if (Ismultipart) {//Create a File Upload object Fileitemfactory factory = new Diskfileitemfactory (); Servletfileupload upload = new Servletfileupload (factory);
Iterator items;
try {//Resolve all file contents submitted by the form items = upload.parserequest (request). iterator ();
while (Items.hasnext ()) {Fileitem item = (Fileitem) items.next ();
if (!item.isformfield ()) {//Remove file name of uploaded file String name = Item.getname ();
String fileName = name.substring (name.lastindexof (' \ \ ') +1,name.length ());
String Path = Request.getrealpath ("file") +file.separatorchar+filename;
Upload file UploadedFile = new files (path);
Item.write (UploadedFile);
Print Upload success Information Response.setcontenttype ("text/html");
Response.setcharacterencoding ("gb2312");
PrintWriter out = Response.getwriter ();
Out.print ("<font size= ' 2 ' > uploaded file as:" +name+ "<br>");
Out.print ("Saved address is:" +path+ "</font>");
(Exception e) {//TODO auto-generated catch block E.printstacktrace ();
}
}
}
}
Note: Create a new file folder in the Webroot directory of your project to store the location of your uploaded files.