package toolkie;
import java.io.File;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
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;
import java.util.*;
public class UploadTool {
private int buffersize = 4096;
private int SizeMax = 1024 * 1024;// 1Mbyte最大檔案大小
private File tempfile = null;
private String def_upload_dir = null;
// 用來存parameter
private Map map = null;
private Map uploadlist = null;
// 處始化時把給request把所有的值取出,存入map
public UploadTool(HttpServletRequest request)
throws FileUploadException,
UnsupportedEncodingException {
map = new HashMap();
uploadlist = new HashMap();
// 建立一個以disk-base的檔案物件
DiskFileItemFactory factory = new DiskFileItemFactory();
// 初始化內容
// 傳送所用的buffer空間
factory.setSizeThreshold(buffersize);
// The directory in which temporary files will be located.
factory.setRepository(tempfile);
// 建立一個檔案上傳的物件
ServletFileUpload upload = new ServletFileUpload(factory);
// 最大檔案大小
upload.setSizeMax(SizeMax * 10);
// 每一個Fileitem代表一個form上傳的物件內容ex input type="text"
List items = null; // 會產生 FileUploadException
// 把資料從request取出
items = upload.parseRequest(request); // Parse the request
Iterator iter = items.iterator();
while (iter.hasNext()) {// 先把所有參數取得而不先write to file
FileItem item = (FileItem) iter.next();
// 一般文字欄位
if (item.isFormField()) {
map.put(item.getFieldName(), item.getString("Big5"));
System.out.println("上傳檔案的其它參數:"
+ item.getFieldName() + "="
+ item.getString("Big5"));
} else {// 上傳檔案欄位
// or it's a file upload request
if (item.getSize() > 0) {
uploadlist.put(item.getFieldName(), item);
System.out.println("上傳檔案:" + item.getFieldName());
}
}
}
}
// 設定檔案上傳後存放的地方
public void setUploadDir(String upload_dir) {
this.def_upload_dir = upload_dir;
}
// 取得所有欄位,包含一般欄位及上傳的欄位
public Map getAllParameter() {
Map rvalue = new HashMap();
rvalue.putAll(map);
rvalue.putAll(uploadlist);
return rvalue;
}
// 取得某一欄位的值,一般欄位
public String getParameter(String FieldName) {
if (map.containsKey(FieldName))
return String.valueOf(map.get(FieldName));
else
return null;
}
// 取得某一欄位的值,上傳欄位
public FileItem getUploadParameter(String FieldName) {
if (uploadlist.containsKey(FieldName))
return (FileItem) uploadlist.get(FieldName);
else
return null;
}
// 檢查上傳資料是否正確
public String checkUpload() {
Iterator iter = uploadlist.keySet().iterator();
while (iter.hasNext()) {
Object Name = iter.next();
FileItem item = (FileItem) uploadlist.get(Name);
String itename = item.getName();
System.out.println("上傳的檔案為:" + itename);
if (item.getSize() > SizeMax)
return "檔案太大!";
}
return "";
}
// 開始上傳
public String doUpload(FileItem item, String fileName) {
String str = "";
long sizeInBytes = item.getSize();
// 碓認上傳資料是否有誤
if (sizeInBytes > SizeMax)
return "檔案太大!";
if (sizeInBytes > 0) {
int index = -1;
String itename = null;
if ((index = item.getName().lastIndexOf("\\")) != -1)
itename = item.getName().substring(index,
item.getName().length());
else
itename = item.getName();
// 副檔名
String formatName = itename.substring(
itename.length() - 4,
itename
.length());
fileName = (fileName + formatName).toLowerCase();
System.out.println("上傳檔案檔案名稱:" + fileName);
File uploadedFile = new File(def_upload_dir + fileName);
// 會產生 Exception
try {
item.write(uploadedFile);
} catch (Exception e) {
System.out.println("上傳失敗!" + e.toString());
str = "上傳失敗!";
}
// 會產生 Exception
}
return str;
}
// 是否存在此上傳欄位資料
public boolean isExtUpload(String fileName) {
return uploadlist.containsKey(fileName);
}
}
您好,我下載您的範例後執行後,eclipse會回報找不到CLASS
我就加入了
再執行一次變成了下面的錯誤
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:268)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
請問我的問題是什麼原因產生的呢?
謝謝
[回應]
yku Replay:
七月 27th, 2010 at 4:50 下午
這應該是您未在classpath裡加入需要的jar檔
第三方的jar檔
Apache Filupload及Apache common io
你可以在文章一開始的地方取得連接,下載後解開裡面的jar
然後開啟eclipse專案結點按右鍵properties->Java Build Path->Libraies 載入這些jar檔
或著你可以把jar檔放到你載案目錄下的web-inf/lib目錄下,也有一樣的效果(如果是tomcat Server的話)
[回應]
不好意思,打擾了,我參照你的程式碼,去實作檔案上傳的功能,
但是在本機端測試可以成功將圖片上傳至
C:\tomcat\webapps\Knowledge2\pic\
但是在上傳至我自己的主機上運作,在上傳檔案之後仍出現 上傳成功
但實際進入電腦裡面 pic的資料夾卻沒有檔案存在
/var/lib/tomcat6/webapps/Knowledge/pic\
upLoad_DIR=this.getServletContext().getRealPath("/")+"pic\\";
這是我在上傳檔案的jsp頁面 所設定的路徑,
因為沒有出現實際的錯誤訊息,所以才冒昧詢問一下,是否有相關的修正方向,可以提供給我參考
不好意思,謝謝
[回應]
yku Replay:
八月 16th, 2010 at 9:51 下午
原始碼跟linux的環境是那一種可以給我一下嘛?
我幫你架起來試看看^^
有可能是你Linux給tomcat的權限不夠 有幾個地方要設
一個是tomcat啟動的user
一個是java的policy
還有tomcat好像也要地方設
建議你用下載的tomcat解壓縮來設定 可以參考我的文章
用agt-get好像有這種問題...
回答不知道是不是你想要的
[回應]