在java裡實作檔案上傳的元件好多,如jspSmartUpload、commons-fileupload,但是jspSmartUpload差不多淘汰了。
在網上找了下 apache的commons-fileupload相關的使用,調通了程式,放在這裡以後好直接使用。。
用到的jar包:(到www.apache.org下載下傳即可)
commons-fileupload-1.2.1.jar
commons-io-1.4.jar
網上還有更詳細的用法:
http://www.cnblogs.com/yyw84/archive/2007/06/27/797652.html
由于代碼太多,如果大家有興趣,可以自己去參考參考。
這是我自己機器上通過的簡單的代碼,放在下面:
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>FileUpload</servlet-name>
<servlet-class>FileUpload.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUpload</servlet-name>
<url-pattern>/servlet/FileUploadServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>fileUpload.jsp</welcome-file>
</welcome-file-list>
</web-app>
FileUpload.javapackage FileUpload;
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 String appRealPath = this.getServletContext().getRealPath("/"); //擷取web app的實體路徑
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");
response.setCharacterEncoding("UTF-8"); // 設定字元編碼為UTF-8, 這樣支援漢字顯示
// 執行個體化一個硬碟檔案工廠,用來配置上傳元件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4096);// 設定上傳檔案時用于臨時存放檔案的記憶體大小,這裡是4K.多于的部分将臨時存在硬碟
dfif.setRepository(new File(appRealPath + "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=\" " + request.getContextPath() + "/fileUpload.jsp" + " \" target=\"_top\">傳回</a>");
return;
}
e.printStackTrace();
}
// 沒有檔案上傳
if (fileList == null || fileList.size() == 0) {
out.println("請選擇上傳檔案<p />");
out.println("<a href=\" " + request.getContextPath() + "/fileUpload.jsp" + " \" 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=\" " + request.getContextPath() + "/fileUpload.jsp" + " \" 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("<a href=\" " + request.getContextPath() + "/fileUpload.jsp" + " \" target=\"_top\">傳回</a>");
return;
}
long now = System.currentTimeMillis();
// 根據系統時間生成上傳後儲存的檔案名
String prefix = String.valueOf(now);
// 儲存的最終檔案完整路徑,儲存在web根目錄下的ImagesUploaded目錄下
String u_name = appRealPath + "ImagesUploaded\\"
+ prefix + "." + t_ext;
try {
// 儲存檔案
fileItem.write(new File(u_name));
out.println("檔案上傳成功. 已儲存為: " + prefix + "." + t_ext
+ " 檔案大小: " + size + "位元組<p />");
out.println("<a href=\" " + request.getContextPath() + "/fileUpload.jsp" + " \" target=\"_top\">繼續上傳</a>");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void init() throws ServletException {
// Put your code here
}
}
fileUpload.jsp<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'fileUpload.jsp' starting page</title>
</head>
<body>
<form action="<%= request.getContextPath() %>/servlet/FileUploadServlet" method="post" enctype="multipart/form-data" >
<input type="file" name="fileUpload" />
<input type="submit" value="upload" />
</form>
</body>
</html>