此篇文章爲轉載,原出處:http://www.blogjava.net/cooky/archive/2007/10/02/150176.html
前幾天搞文件上傳, Google到了Apache 的 commons-fileupload-1.2.jar 上傳組件, 研究了API然後結合Hibernate實現了上傳圖片
並保存到MySQL數據庫. 今天重新寫了一遍, 由於不需要保存到數據庫了, 就實現了保存成文件格式.
我的這個FileUpload web工程源文件下載如下 : FileUpload.rar . 解壓到當前文件夾後直接剪切到 Tomcat 主目錄下的 webapps
目錄下, 啓動 Tomcat 後在瀏覽器輸入 http://localhost:8080/FileUpload/upload.html 查看演示.
我是用Eclipse 開發. 首先, 下載兩個開發包: commons-fileupload 和 commons-io(這個在應用commons-fileupload時會用到).
這兩個開發包(jar文件) 在我前面提供的FileUpload 工程下的WEB-INF/lib下可以找到, 你也可以到官方下載:
到 http://commons.apache.org/downloads/download_fileupload.cgi 下載 commons-fileupload-1.2.jar
組件包 (直接下載地址: http://apache.mirror.phpchina.com/commons/fileupload/binaries/commons-fileupload-1.2-bin.zip),
到 http://commons.apache.org/downloads/download_io.cgi 下載 commons-io-1.3.2 組件包(直接下載地址:
http://apache.mirror.phpchina.com/commons/io/binaries/commons-io-1.3.2-bin.zip).
啓動Eclipse, 新建Web Project, 取名 FileUpload. 然後在WebRoot文件夾(Web根文件夾)下新建兩個文件夾(New->Folder) :
ImagesUploaded 和 ImagesUploadTemp, 分別用來存放上傳文件和上傳時的臨時文件,稍後代碼裏會用到.
在WebRoot 文件夾下新建文件upload.html, 用來提供上傳用的form. 源代碼如下:
右擊src, 新建一個Servlet: FileUploadServlet, 路徑設爲src/FileUploadServlet . 保存後WebRoot/WEB-INF/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>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/FileUploadServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>upload.html</welcome-file>
</welcome-file-list>
</web-app>
其中,我把<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> 的歡迎文件設爲了upload.html,
這樣等完成後可能直接用http://localhost:8080/FileUpload/ 來訪問upload.html. 不改的話, 可以在http://localhost:8080/FileUpload/upload.html
頁面上傳文件. 在寫FileUploadServlet 之前, 先將之前下載的commons-fileupload 和commons-io 組件包壓縮文件解壓出來, 把裏面的
commons-fileupload-1.2.jar (lib文件夾下) 和 commons-io-1.3.2.jar 拷到WebRoot/WEB-INF/lib 文件夾下, 以便使用它們的功能.
FileUploadServlet.java 的源代碼如下, 附有詳細註解:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet extends HttpServlet {
public FileUploadServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final long MAX_SIZE = 3 * 1024 * 1024;// 設置上傳文件最大爲 3M
// 允許上傳的文件格式的列表
final String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "txt",
"doc", "docx", "mp3", "wma", "m4a" };
response.setContentType("text/html");
// 設置字符編碼爲UTF-8, 這樣支持漢字顯示
response.setCharacterEncoding("UTF-8");
// 實例化一個硬盤文件工廠,用來配置上傳組件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4096);// 設置上傳文件時用於臨時存放文件的內存大小,這裏是4K.多於的部分將臨時存在硬盤
dfif.setRepository(new File(request.getRealPath("/")
+ "ImagesUploadTemp"));// 設置存放臨時文件的目錄,web根目錄下的ImagesUploadTemp目錄
// 用以上工廠實例化上傳組件
ServletFileUpload sfu = new ServletFileUpload(dfif);
// 設置最大上傳尺寸
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = response.getWriter();
// 從request得到 所有 上傳域的列表
List fileList = null;
try {
fileList = sfu.parseRequest(request);
} catch (FileUploadException e) {// 處理文件尺寸過大異常
if (e instanceof SizeLimitExceededException) {
out.println("文件尺寸超過規定大小:" + MAX_SIZE + "字節<p />");
out.println("<a href=\"upload.html\" target=\"_top\">返回</a>");
return;
}
e.printStackTrace();
}
// 沒有文件上傳
if (fileList == null || fileList.size() == 0) {
out.println("請選擇上傳文件<p />");
out.println("<a href=\"upload.html\" target=\"_top\">返回</a>");
return;
}
// 得到所有上傳的文件
Iterator fileItr = fileList.iterator();
// 循環處理所有文件
while (fileItr.hasNext()) {
FileItem fileItem = null;
String path = null;
long size = 0;
// 得到當前文件
fileItem = (FileItem) fileItr.next();
// 忽略簡單form字段而不是上傳域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
continue;
}
// 得到文件的完整路徑
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
if ("".equals(path) || size == 0) {
out.println("請選擇上傳文件<p />");
out.println("<a href=\"upload.html\" target=\"_top\">返回</a>");
return;
}
// 得到去除路徑的文件名
String t_name = path.substring(path.lastIndexOf("\\") + 1);
// 得到文件的擴展名(無擴展名時將得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒絕接受規定文件格式之外的文件類型
int allowFlag = 0;
int allowedExtCount = allowedExt.length;
for (; allowFlag < allowedExtCount; allowFlag++) {
if (allowedExt[allowFlag].equals(t_ext))
break;
}
if (allowFlag == allowedExtCount) {
out.println("請上傳以下類型的文件<p />");
for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
out.println("*." + allowedExt[allowFlag]
+ " ");
out.println("<p /><a href=\"upload.html\" target=\"_top\">返回</a>");
return;
}
long now = System.currentTimeMillis();
// 根據系統時間生成上傳後保存的文件名
String prefix = String.valueOf(now);
// 保存的最終文件完整路徑,保存在web根目錄下的ImagesUploaded目錄下
String u_name = request.getRealPath("/") + "ImagesUploaded/"
+ prefix + "." + t_ext;
try {
// 保存文件
fileItem.write(new File(u_name));
out.println("文件上傳成功. 已保存爲: " + prefix + "." + t_ext
+ " 文件大小: " + size + "字節<p />");
out.println("<a href=\"upload.html\" target=\"_top\">繼續上傳</a>");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void init() throws ServletException {
// Put your code here
}
}
保存後部署項目(MyEclipse下直接點擊Deploy J2EE...按鈕, 然後選擇Tomcat服務器). 沒有MyEclipse的話, 把WebRoot 拷到
Tomcat 主目錄下的webapps 目錄下, 並重命名爲 FileUpload 然後啓動Tomcat. (或直接下載我在文章開始提供的工程打包rar文件).
最後打開瀏覽器, 輸入url:
http://localhost:8080/FileUpload/upload.html .