java文件上传commons-fileupload


常用的上传组件:  

Apache 的 Commons FileUpload

jspSmartUpload

JavaZoom的UploadBean

 

jspSmartUpload 简单易用,但是它好像不是开源的,也不怎么更新了,它上传要把文件放入内存,不适合传大文件,

推荐使用commons-fileupload

开源组件,有更新,可以上传大文件。Struts也是采用它处理上传。

 

commons-fileupload下载地址:

http://commons.apache.org/fileupload/

下载:commons-fileupload-1.3-bin.zip    得到:commons-fileupload-1.3.jar

http://commons.apache.org/io/

下载:commons-io-2.2-bin.zip       得到:commons-io-2.2.jar

 

upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>using commons Upload to upload file</title>
</head>
<style>
* {
	font-family: "宋体";
	font-size: 14px
}
</style>
<body>
	<p align="center">请您选择需要上传的文件</p>
	<form id="form1" name="form1" method="post"
		action="servlet/fileServlet" enctype="multipart/form-data">
		<table border="0" align="center">
			<tr>
				<td>上传人:</td>
				<td><input name="name" type="text" id="name" size="20"></td>
			</tr>
			<tr>
				<td>上传文件:</td>
				<td><input name="file" type="file" size="20"></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit" name="submit" value="提交"> <input
					type="reset" name="reset" value="重置"></td>
			</tr>
		</table>
	</form>
</body>
</html>

 

FileUploadServlet.java
package com.urt.module.upload;

import java.io.File;
import java.io.IOException;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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;

/**
 * 上传Servlet
 * @author happyqing
 * 2013.10.29
 */
public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = -7744625344830285257L;
	private ServletContext sc;
	private String savePath;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void init(ServletConfig config) {
		// 在web.xml中设置的一个初始化参数
		savePath = config.getInitParameter("savePath");
		sc = config.getServletContext();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					System.out.println("表单参数名:" + item.getFieldName()
							+ ",表单参数值:" + item.getString("UTF-8"));
				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						System.out.println("上传文件的大小:" + item.getSize());
						System.out.println("上传文件的类型:" + item.getContentType());
						// item.getName()返回上传文件在客户端的完整路径名称
						System.out.println("上传文件的名称:" + item.getName());

						File tempFile = new File(item.getName());

						// 上传文件的保存路径 //运行目录下
						File file = new File(sc.getRealPath("/") + savePath,
								tempFile.getName());
						item.write(file);
						request.setAttribute("upload.message", "上传文件成功!");
					} else {
						request.setAttribute("upload.message", "没有选择上传文件!");
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("upload.message", "上传文件失败!");
		}
		request.getRequestDispatcher("/uploadResult.jsp").forward(request,
				response);
	}
}
 
uploadResult.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>uploadResult</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

</head>

<body>
	${requestScope['upload.message'] }
	<a href="/upload/uploadFile.jsp">上传文件</a>
</body>
</html>

 

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>redcrossModule</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>upload.jsp</welcome-file>
	</welcome-file-list>

	<servlet>
		<description></description>
		<display-name>FileUploadServlet</display-name>
		<servlet-name>FileUploadServlet</servlet-name>
		<servlet-class>com.urt.module.upload.FileUploadServlet</servlet-class>
		<!--设置初始化参数 -->
		<init-param>
			<param-name>savePath</param-name>
			<param-value>upload</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>FileUploadServlet</servlet-name>
		<url-pattern>/servlet/fileServlet</url-pattern>
	</servlet-mapping>

</web-app>
 
参考:
使用 common-fileupload 实现文件上传 
Java 文件上传组件 Apache Commons FileUpload 应用指南

你可能感兴趣的:(java,upload)