對這文章發表回應
發表限制: 非會員 可以發表
發表者: 冷日 發表時間: 2008/3/18 3:28:56
HTML表單(form)裡面現在都支援了FILE類型(TYPE="file"),
允許使用者將電腦裡的檔案透過表單的方式傳送到SERVER,
上傳的時候,編碼是採用 MULTIPART/FORM-DATA
和一般表單的編碼是不一樣的,
所以SERVLET無法以一般的表單擷取方式取得資料,
此時的request物件的getParameter方法是無用武之地的!
許多公司或團體就因應這問題提出了一些方案,
有也相關的API可以參考,
再此列出一些比較有名的方案:
jspSmart - jspSmartUpload ( http://www.jspsmart.com/ )
O'Pielly - MultipartRequest ( http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartRequest.html )
Jakarta - fileupload ( http://jakarta.apache.org/commons/fileupload/ )
但是因為jspSmart 已經關佔了,所以此處不再多做說明,
冷日分別針對另外兩郭方法提出範例!
O'Pielly - MultipartRequest :
Jakarta - fileupload :
這裡都只是很簡單的用法,
目的只是抓到上傳的檔案,
供大家參考!
允許使用者將電腦裡的檔案透過表單的方式傳送到SERVER,
上傳的時候,編碼是採用 MULTIPART/FORM-DATA
和一般表單的編碼是不一樣的,
所以SERVLET無法以一般的表單擷取方式取得資料,
此時的request物件的getParameter方法是無用武之地的!
許多公司或團體就因應這問題提出了一些方案,
有也相關的API可以參考,
再此列出一些比較有名的方案:
jspSmart - jspSmartUpload ( http://www.jspsmart.com/ )
O'Pielly - MultipartRequest ( http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartRequest.html )
Jakarta - fileupload ( http://jakarta.apache.org/commons/fileupload/ )
但是因為jspSmart 已經關佔了,所以此處不再多做說明,
冷日分別針對另外兩郭方法提出範例!
O'Pielly - MultipartRequest :
import com.oreilly.servlet.*;
MultipartRequest mr = new MultipartRequest(req , req.getRealPath("/") + "tmp" , FILE_MAX_SIZE);
File uf = mr.getFile("uploadfile");
Jakarta - fileupload :
import org.apache.commons.fileupload.*;
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
DiskFileUpload fu = new DiskFileUpload();
// maximum size before a FileUploadException will be thrown
fu.setSizeMax(1000000);
// maximum size that will be stored in memory
fu.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
fu.setRepositoryPath("/tmp");
List fileItems = fu.parseRequest(req);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator i = fileItems.iterator();
String comment = ((FileItem)i.next()).getString();
FileItem fi = (FileItem)i.next();
// filename on the client
String fileName = fi.getName();
// write the file
fi.write("/www/uploads/" + fileName);
}
這裡都只是很簡單的用法,
目的只是抓到上傳的檔案,
供大家參考!