`
DavyJones2010
  • 浏览: 155057 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

JavaWeb: How to use commons-fileupload-1.3 for File Upload

阅读更多

1. Requirements:

    1) A safer way to handle file upload by using commons-fileupload-1.3.jar provided by Apache Foundation.

    2) Using simple JSP/Servlet for a simple mock up.

 

2. Preconditions:

    1) Import related jars.    

        1) Import JRE-System-Library

        2) Import J2EE 5.0 Library <jsp-api.jar, servlet-api.jar>

        3) Import commons-io-2.4.jar

        4) Import commons-fileupload-1.3.jar

    2) Build a basic JavaWeb project.

        1) Dir hierarchy is correctly configured

        2) web.xml

        3) index.jsp

    3) Correctly deployed on Tomcat 6.x

 

3. Related Files

    1) index.jsp

<html>
<head>
<title>File Upload</title>
</head>
<body>
	<form enctype="multipart/form-data" action="FileUploadServlet"
		method="post">
		File to upload: <input type="file" name="upfile" /><br /> Notes about
		the file: <input type="text" name="note" /><br /> <br /> <input
			type="submit" value="Upload" />
	</form>
</body>
</html>

    Comments:

        1) Use basic Form for illustration. Pay attention to that enctype="multipart/form-data" must be point out.

    2) web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
  	<servlet-name>FileUploadServlet</servlet-name>
  	<servlet-class>edu.xmu.servlet.FileUploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>FileUploadServlet</servlet-name>
  	<url-pattern>/FileUploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

    Comments: Correctly mapping is essential!

    3) edu.xmu.servlet.FileUploadServlet.java

package edu.xmu.servlet;

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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		// TODO Auto-generated method stub
		System.out.println("doGet");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		// TODO Auto-generated method stub
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);

		System.out.println("isMultipart = " + isMultipart);

		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();
                // Set the repository to store temp files that uploaded.
		File repository = new File("C:/YangKunLun/UploadRepository");
		factory.setRepository(repository);

		ServletFileUpload upload = new ServletFileUpload(factory);

		try
		{
			List<FileItem> items = upload.parseRequest(req);

			Iterator<FileItem> iter = items.iterator();

			while (iter.hasNext())
			{
				FileItem item = iter.next();

				if (item.isFormField())
				{
					processFormField(item);
				} else
				{
					processUploadedFile(item);
				}
			}
		} catch (FileUploadException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("doPost");
	}

	private void processFormField(FileItem item)
	{
		String name = item.getFieldName();
		String value = item.getString();
		System.out.println("name = " + name + ", value = " + value);
	}

	private void processUploadedFile(FileItem item)
	{
		String fieldName = item.getFieldName();
		String fileName = item.getName();
		String contentType = item.getContentType();
		boolean isInMemory = item.isInMemory();
		long sizeInBytes = item.getSize();

		System.out.println("fieldName = " + fieldName + ", fileName = "
				+ fileName + ", contentType = " + contentType
				+ ", isInMemory = " + isInMemory + ", sizeInBytes = "
				+ sizeInBytes);
	}
}

    Comments:

        1) Output look like this:

isMultipart = true
fieldName = upfile, fileName = msvcr71.dll, contentType = application/x-msdownload, isInMemory = false, sizeInBytes = 348160
name = note, value = Hello
doPost

    3) Enhanced edu.xmu.servlet.FileUploadServlet.java

package edu.xmu.servlet;

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.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet
{
	private final static String bufferPath = "C:/YangKunLun/UploadRepository";
	private final static String destPath = "C:/YangKunLun/UploadStore";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		// TODO Auto-generated method stub
		System.out.println("doGet");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		// TODO Auto-generated method stub
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);

		System.out.println("isMultipart = " + isMultipart);

		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		File repository = new File(bufferPath);
		factory.setRepository(repository); // Set the buffer directory.
		factory.setSizeThreshold(1024 * 2); // Set the size of buffer.

		ServletFileUpload upload = new ServletFileUpload(factory);

		// Create a progress listener
		ProgressListener progressListener = new ProgressListener()
		{
			private long megaBytes = -1;

			/**
			 * pBytesRead: The total number of bytes, which have been read so
			 * far pContentLength: The total number of bytes, which are being
			 * read. May be -1, if this number is unknown. pItems : The number
			 * of the field, which is currently being read. (0 = no item so far,
			 * 1 = first item is being read, ...)
			 */
			public void update(long pBytesRead, long pContentLength, int pItems)
			{
				long mBytes = pBytesRead / 1000000;
				// "if" statement is for the purpose of reduce the progress
				// listeners activity
				// For example, you might emit a message only, if the number of
				// megabytes has changed:
				if (megaBytes == mBytes)
				{
					return;
				}
				megaBytes = mBytes;
				System.out.println("We are currently reading item " + pItems);
				if (pContentLength == -1)
				{
					System.out.println("So far, " + pBytesRead
							+ " bytes have been read.");
				} else
				{
					System.out.println("So far, " + pBytesRead + " of "
							+ pContentLength + " bytes have been read.");
				}
			}
		};

		upload.setProgressListener(progressListener);

		try
		{
			List<FileItem> items = upload.parseRequest(req);

			Iterator<FileItem> iter = items.iterator();

			while (iter.hasNext())
			{
				FileItem item = iter.next();

				if (item.isFormField())
				{
					processFormField(item);
				} else
				{
					processUploadedFile(item);
				}
			}
		} catch (FileUploadException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("doPost");
	}

	private void processFormField(FileItem item)
	{
		String name = item.getFieldName();
		String value = item.getString();
		System.out.println("name = " + name + ", value = " + value);
	}

	private void processUploadedFile(FileItem item) throws Exception
	{
		String fieldName = item.getFieldName();
		String fileName = item.getName();
		String contentType = item.getContentType();
		boolean isInMemory = item.isInMemory();
		long sizeInBytes = item.getSize();

		System.out.println("fieldName = " + fieldName + ", fileName = "
				+ fileName + ", contentType = " + contentType
				+ ", isInMemory = " + isInMemory + ", sizeInBytes = "
				+ sizeInBytes);
		File fileToSave = new File(destPath, fileName);

		item.write(fileToSave);
	}
}

    Output looks like this:

isMultipart = true
We are currently reading item 0
So far, 4096 of 20719060 bytes have been read.
We are currently reading item 1
So far, 1000042 of 20719060 bytes have been read.
We are currently reading item 1
So far, 2000084 of 20719060 bytes have been read.
We are currently reading item 1
So far, 3000126 of 20719060 bytes have been read.
We are currently reading item 1
So far, 4000168 of 20719060 bytes have been read.
We are currently reading item 1
So far, 5000210 of 20719060 bytes have been read.
We are currently reading item 1
So far, 6000252 of 20719060 bytes have been read.
We are currently reading item 1
So far, 7000294 of 20719060 bytes have been read.
We are currently reading item 1
So far, 8000336 of 20719060 bytes have been read.
We are currently reading item 1
So far, 9000378 of 20719060 bytes have been read.
We are currently reading item 1
So far, 10000420 of 20719060 bytes have been read.
We are currently reading item 1
So far, 11000462 of 20719060 bytes have been read.
We are currently reading item 1
So far, 12000504 of 20719060 bytes have been read.
We are currently reading item 1
So far, 13000546 of 20719060 bytes have been read.
We are currently reading item 1
So far, 14000588 of 20719060 bytes have been read.
We are currently reading item 1
So far, 15000630 of 20719060 bytes have been read.
We are currently reading item 1
So far, 16000672 of 20719060 bytes have been read.
We are currently reading item 1
So far, 17000714 of 20719060 bytes have been read.
We are currently reading item 1
So far, 18000756 of 20719060 bytes have been read.
We are currently reading item 1
So far, 19000798 of 20719060 bytes have been read.
We are currently reading item 1
So far, 20000840 of 20719060 bytes have been read.
fieldName = upfile, fileName = src.zip, contentType = application/x-zip-compressed, isInMemory = false, sizeInBytes = 20718763
name = note, value = Hello
doPost

    Comments:

    1) Added progress listener.

    2) Added destination folder to verify output works.

 

P.S

     Related sites:

     1) http://commons.apache.org/proper/commons-fileupload/

     2) http://commons.apache.org/proper/commons-fileupload/using.html

分享到:
评论

相关推荐

    commons-dbcp-1.4&&commons-pool-1.3.jar

    标题中的"commons-dbcp-1.4&&commons-pool-1.3.jar"指的是Apache Commons的两个重要组件:DBCP(Database Connection Pool)1.4版本和Pool 1.3版本。这两个组件在Java Web开发中扮演着关键角色,尤其在数据库连接...

    commons-fileupload-1.3.3和commons-io-2.6

    Commons Fileupload是Apache commons众多开源组件中的一员,这种类库用于解析二进制数据流,一些框架如Struts里集成了Apache CommonFileupload类库来实现文件上传。

    JavaWeb需要用到的jar包_jar包_javaweb_commons-dbutils-1.3_

    1. **commons-dbutils-1.3**: Commons-DbUtils是Apache的一个开源项目,它提供了一个简单且实用的数据库操作工具包。DbUtils的主要功能包括:连接池管理、SQL执行、结果集处理等。DbUtils与JDBC结合使用,可以避免...

    commons-fileupload-1.2.1

    javaweb上传下载所需jar包 啊

    commons-文件上传必备jar包二合一-io1.4+fileupload1.2.1

    Apache Commons项目为开发者提供了两个非常重要的库:Commons IO和Commons FileUpload,这两个库使得文件上传操作变得简单易行。在"commons-文件上传必备jar包二合一-io1.4+fileupload1.2.1"中,包含了这两个库的...

    JavaWeb上传文件的所有Jar ,commons-fileupload-1.3.1等...

    总之,Apache Commons FileUpload库是实现JavaWeb文件上传功能的强大工具。通过合理配置和编程,可以构建稳定、安全、高效的文件上传系统。在实际项目中,还可能需要结合其他库,如Spring MVC或Struts2,它们已经...

    commons-fileupload文件上传组件中文教程--张孝祥写的

    本文档旨在通过详细解读《深入体验 JavaWeb 开发内幕—高级特性》一书中关于Apache Commons FileUpload的部分内容,帮助初学者快速掌握文件上传功能的实现。 #### 二、准备工作 1. **环境搭建**: - **Tomcat版本...

    commons-beanutils-1.8.0.jar、commons-logging-1.1.1.jar

    Apache Commons BeanUtils是Java开发中的一个实用工具库,它提供了对JavaBeans操作的强大支持。这个库简化了在Java应用程序中处理Java对象的属性的工作。在本篇中,我们将深入探讨`commons-beanutils-1.8.0.jar`和`...

    commons相关jar包

    commons-codec-1.3.jar commons-collections-3.2.1.jar commons-collections-testframework-3.2.1.jar commons-dbcp-1.2.1.jar commons-digester.jar commons-discovery-0.2.jar commons-fileupload-1.2.1.jar ...

    commons-io-2.7.jar

    前一段时间学习多线程,狂神老师说需要用到里面的jar包进行资源下载的练习。找了好久才找到了这个官方的jar包合集,在这里免费的送给各位老铁们,希望大家一起努力学习,在秃头的道路上一往无前。

    根据commons-fileupload制作的个人上传工具类

    根据commons-fileupload制作的个人上传工具类,作者为Z-HaiSome(本人)。制作这个工具类为了更容易在jsp页面获取上传文件,做出简化操作。刚接触javaWEB,才疏学浅,如有错误还请指出,一起学习~

    commons-beanutils.jar、commons-logging.jar两个包

    beanUtils 方便访问javaBean 附带支持框架 logging jar包,Apache提供的这个beanutils包极大方便了javabean的 操作。包含了最新的commons-beanutils-1.9.3.jar,以及其依赖的commons-logging-1.2.jar包

    JavaWeb常用基本jar包.zip

    JavaWeb常用jar包整合,这里用的数据库jar包是5.1.37可以连5.5.40的数据库的,如果数据库版本较高记得更改,其余包含c3p0-0.9.1.2、commons-beanutils-1.9.4、commons-dbcp-1.4、commons-dbutils-1.7、commons-...

    JavaWeb课程设计期末大作业-学生信息管理系统源码+数据库+详细文档说明

    JavaWeb课程设计期末大作业-学生信息管理系统源码+数据库+详细文档说明,含有代码注释,满分课程设计资源,新手也可看懂,期末大作业、课程设计、高分必看,下载下来,简单部署,就可以使用。该项目可以作为课程设计...

    JavaWeb课程设计期末大作业-学生信息管理系统源码+数据库+文档说明(高分项目)

    JavaWeb课程设计期末大作业-学生信息管理系统源码+数据库+文档说明(高分项目),含有代码注释,满分课程设计资源,新手也可看懂,期末大作业、课程设计、高分必看,下载下来,简单部署,就可以使用。该项目可以作为...

    mchange-commons-java-0.2.3.4.jar

    javaweb常用jar包,javaee框架常用jar包,亲测可用,若需其他版本可给我留言

    c3p0-0.9.0+mchange-commons-java-0.2.3.4.jar

    标题中的“c3p0-0.9.0+mchange-commons-java-0.2.3.4.jar”提到了两个关键的Java库:c3p0和mchange-commons-java。这两个库在Java Web开发中扮演着重要的角色,特别是对于数据库连接管理和资源优化。 c3p0是一个...

    javaweb上传下载小案例--简单网盘

    利用commons-fileupload-1.2.1.jar实现上传下载,很简单的案例,连接数据库存储信息 详见:http://www.cnblogs.com/xiaoduc-org/p/5415797.html

    apache-log4j-2.3-bin和commons-logging-1.2

    Apache Log4j 2.3 和 Commons Logging 1.2 是两个在Java Web开发中广泛使用的日志处理库。这两个库对于记录应用程序的运行时信息、调试错误和监控系统状态至关重要。 **Apache Log4j 2.3** Log4j 是 Apache 组织...

    前期JAVAWEB开发所需jar包资源

    拥有前期javaweb开发的大部分jar包,包含c3p0-0.9.5.2.jar;druid-1.0.9.jar;commons-beanutils-1.9.4.jar;commons-fileupload-1.4.jar;commons-io-2.5.jar;commons-logging-1.2.jar;jackson-annotations-2.2.3...

Global site tag (gtag.js) - Google Analytics