Handling file upload using commons file upload API

Java Servlet file upload example

This Servlet File Upload tutorial explains how to handle the file upload in Servlets.

This tutorial explains

  1. Handling file upload using apache commons-file file upload API.

File upload specification is contained in RFC 1867 ‘form based file upload in HTML’.

Note: Servlet 3.0 Specification has built in file upload support. With servlet 3.0, you don't need to use any external library like commons file upload. Read this @MultipartConfig : Servlet 3.0 File Upload Example For more details on built in file upload support in servlet 3.0 specification.

Handling file upload using commons file upload API

The commons File Upload package makes it easy to add robust, high performance, file upload capacity to your Servlets and web applications.

Download and install Commons File Upload package

First of all, download the latest version of commons file upload package from here. FileUpload depends on Commons IO package, so download the version mentioned on the FileUpload dependency page. t the time of writing this tutorial, the latest version of Commons File Upload is 1.2.1 which depends on Commons IO version 1.3.2. Installation is very easy. Extract both of the downloaded zip files and put commons-fileupload-1.2.1.jar and commons-io-1.3.2.jar jar files into the WEB-INF/lib folded of your web application.

The next step is to create the HTML file.

Create the HTML file with file input field

It is very easy to write the HTML file that supports file upload.

  1. Set the content type of the HTML form to multipart/form-data.
  2. Add the file input type filed into the HTML form.

As specified in RFC1867, to support the file upload, Content type of the POST request must be set to multipart/form-data. This can be done by setting the value of ENCTYPE attribute of HTML form to multipart/form-data

<form action=”/FileUploadServlet” ENCTYPE=”mulipart/form-data” method=”POST”>

File input type field displays a file input box which allows user to select a file to upload.
<input type=”file” name=”file”/>

There can be any number of file input fields in a HTML form.

Copy the following code into upload.html file. Save the file directly under the web application root directory


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head></head>
<body>
	<p>Commons File Upload Example</p>
	<form action="CommonsFileUploadServlet" enctype="multipart/form-data"
		method="POST">
		<input type="file" name="file1"><br> <input type="text"
			name="param" value="中文" /><br> <input type="Submit"
			value="Upload File"><br>
	</form>
</body>
</html>

The File Upload Servlet

Copy the following code into CommonsFileUploadServlet.java.

package com.test.day15.fileupload;

import java.io.File;

/**
 * Servlet implementation class CommonsFileUploadServlet
 */
public class CommonsFileUploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5456408232882331065L;
	private static final String TMP_DIR_PATH = "c:\\tmp";
	private File tmpDir;
	private static final String DESTINATION_DIR_PATH = "E:/Test File/2012-2-4";
	private File destinationDir;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CommonsFileUploadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if (!tmpDir.exists()) {
			tmpDir.mkdirs();
		}
		if (!tmpDir.isDirectory()) {
			throw new ServletException(TMP_DIR_PATH + " is not a directory");
		}
		destinationDir = new File(DESTINATION_DIR_PATH);
		if (!destinationDir.exists()) {
			destinationDir.mkdirs();
		}
		if (!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH
					+ " is not a directory");
		}

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
		out.println();

		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		/*
		 * Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above
		 * threshold.
		 */
		fileItemFactory.setRepository(tmpDir);

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				/*
				 * Handle Form Fields.
				 */
				if (item.isFormField()) {
					System.out.println("File Name = " + item.getFieldName()
							+ ", Value = " + item.getString("UTF-8"));
					out.println("File Name = " + item.getFieldName()
							+ ", Value = " + item.getString("UTF-8"));
				} else {
					// Handle Uploaded files.
					out.println("Field Name = " + item.getFieldName()
							+ ", File Name = " + item.getName()
							+ ", Content type = " + item.getContentType()
							+ ", File Size = " + item.getSize());
					/*
					 * Write file to the ultimate location.
					 */
					File file = new File(destinationDir, item.getName());
					item.write(file);
				}
				out.close();
			}
		} catch (FileUploadException ex) {
			log("Error encountered while parsing the request", ex);
		} catch (Exception ex) {
			log("Error encountered while uploading file", ex);
		}

	}

}
Compile the CommnonsFileUploadServlet.java file as explained in tutorial Servlet Example and put the class file inside WEB-INF/classes directory.

Web.xml servlet mapping

<servlet>
		<servlet-name>CommonsFileUploadServlet</servlet-name>
		<servlet-class>CommonsFileUploadServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>CommonsFileUploadServlet</servlet-name>
		<url-pattern>/Commonsfileuploadservlet</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>/upload.html</welcome-file>
	</welcome-file-list>	
Create two folders tmp and files under your web application root directory. deploy the application to tomcat server and start the server.
Access the application in browser and upload any file. The file would be uploaded to server and saved under the files directory of the application.



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Apache Commons FileUpload库来上传本地文件。以下是一个简单的示例代码: 1. 首先,你需要在项目中添加commons-fileuploadcommons-io库的依赖,可以在Maven或Gradle中添加以下依赖: Maven: ``` <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> ``` Gradle: ``` implementation 'commons-fileupload:commons-fileupload:1.4' implementation 'commons-io:commons-io:2.8.0' ``` 2. 在你的Servlet或Controller中,编写以下代码: ``` import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet("/upload") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { // 判断是否是文件类型 String fileName = item.getName(); String filePath = "/path/to/upload/folder/" + fileName; File uploadedFile = new File(filePath); item.write(uploadedFile); } } response.getWriter().println("File uploaded successfully!"); } catch (Exception e) { response.getWriter().println("File upload failed!"); e.printStackTrace(); } } } } ``` 这个示例代码将上传的文件保存在`/path/to/upload/folder/`路径下。你可以根据你的实际情况修改保存路径。 3. 在前端,你可以使用HTML表单来上传文件: ``` <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ``` 当用户单击“上传”按钮时,表单将提交到`/upload`URL,然后Servlet将处理上传的文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值