日期:2014-05-19  浏览次数:20730 次

J2EE上传文件至服务器

?昨天整了个J2EE文件下载的code,今天熬夜,凌晨半点了,终于把J2EE文件上传一口气给code下来了...

?

本文以Commons FileUpload为例,展示如何利用Commons FileUpload在J2EE中上传文件。

展示DEMO如下,欢迎拍砖。~—~

有点缺憾,就是没做成进度条的效果,因为目前还没头绪,-_-? .....

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<!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>FileUploadServlet</servlet-name>
		<servlet-class>com.syc.servlet.FileUploadServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>FileUploadServlet</servlet-name>
		<url-pattern>/FileUploadServlet</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

</web-app>

?

?

index.jsp

?

<%@ page language="java" import="java.util.*" contentType="text/html;charset=gbk" pageEncoding="gbk"%>
<html>
<body>
	<form action="FileUploadServlet" enctype="multipart/form-data" method="post">
		<input type="text" name="username" /><br />
		<input type="file" name="myfile" /><br/>
		<input type="file" name="myfile" /><br/>
		<input type="submit" />
	</form>
</body>
</html>

?

FileUploadServlet.java

package com.syc.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
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.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.file