Java component Commons-fileupload File upload Example _java

Source: Internet
Author: User
Tags uuid java web

File upload is very common in Web applications, it is very easy to upload the file in the Java Web environment, because there are already many Java-developed components used for file uploads, this article, for example, demonstrates how to use the most common commons-fileupload components for Java Web application Add File Upload function.

The Commons-fileupload component is one of Apache's open source projects that can be downloaded from http://commons.apache.org/fileupload/ . The component is simple to use, can upload one or more files at a time, and can limit file size.

After downloading unzip the zip package, copy the Commons-fileupload-1.x.jar to Tomcat webapps/your webapp/web-inf/lib/, if the directory does not exist please build the directory yourself.

Create a new Uploadservlet.java for file uploads:

Package com.liaoxuefeng.web;

public class Fileuploadservlet extends HttpServlet {

 private String Uploaddir = "C:\\Temp";

 @Override
 protected void DoPost (HttpServletRequest req, HttpServletResponse resp)
 throws Servletexception, IOException
 {
 //TODO:
 }
}

When the servlet receives a POST request from the browser and implements the file upload in the Dopost () method, we need to traverse fileitemiterator for each fileitemstream:

@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp)
 throws Servletexception, IOException
{
 try {
 servletfileupload upload = new Servletfileupload ();
 Set max file size to 1 MB:
 Upload.setfilesizemax (1024 * 1024);
 Fileitemiterator it = upload.getitemiterator (req);
 Handle with each file: while
 (It.hasnext ()) {
 Fileitemstream item = It.next ();
 if (! Item.isformfield ()) {
 //It is a file upload:
 handlefileitem (item);
 }
 Req.getrequestdispatcher ("success.jsp"). Forward (req, resp);
 catch (Fileuploadexception e) {
 throw new servletexception ("Cannot upload file.", E);
 }
}

Reads the input stream of the uploaded file in the Handlefileitem () method and writes it to the Uploaddir, which is randomly generated by the UUID:

void Handlefileitem (Fileitemstream item) throws IOException {
 System.out.println ("Upload file:" + item.getname ());
 file Newuploadfile = new file (Uploaddir + "/" + Uuid.randomuuid (). toString ());
 byte[] buffer = new byte[4096];
 InputStream input = null;
 OutputStream output = null;
 try {
 input = Item.openstream ();
 Output = new Bufferedoutputstream (new FileOutputStream (Newuploadfile));
 for (;;) {
 int n = input.read (buffer);
 if (n== ( -1)) break
 ;
 Output.write (buffer, 0, N);
 }
 }
 Finally {
 if (input!=null) {
 try {
 input.close ();
 }
 catch (IOException e) {}
 }
 if (Output!=null)} {
 try {
 output.close ();
 }
 catch (IOException e) {}}}}

If you want to read the specified upload folder in the Web.xml configuration file, you can initialize it in the init () method:

@Override public
void init (servletconfig config) throws servletexception {
 super.init (config);
 This.uploaddir = Config.getinitparameter ("dir");
}

Finally, configure the servlet in Web.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE Web-app public
 "-//sun Microsystems, INC.//DTD Web application 2.3//en"
 "http://java.sun.com/dtd/ Web-app_2_3.dtd ">
<web-app>
 <servlet>
 <servlet-name>uploadservlet</ servlet-name>
 <servlet-class>com.liaoxuefeng.web.FileUploadServlet</servlet-class>
 < /servlet>
 <servlet-mapping>
 <servlet-name>UploadServlet</servlet-name>
 < url-pattern>/upload</url-pattern>
 </servlet-mapping>
</web-app>

After you configure the servlet, start Tomcat or resin, and write a simple index.htm test:

 
 

Note action= "Upload" specifies the mapping URL for the fileuploadservlet that handles the uploaded file.

When uploaded successfully, display success.jsp, otherwise, throw an exception. If the uploaded file size exceeds the 1MB we set, we will get a filesizelimitexceededexception.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.