Posted on 2007-02-06 17:19
lixw 閱讀(518)
評(píng)論(0) 編輯 收藏
一、最簡(jiǎn)單的方式:
設(shè)置表單form 的 method=”post” ENCTYPE="multipart/form-data"
通過(guò)
InputStream in =servletRequest.getInputStream();
以流的方式處理,它的缺點(diǎn)就不言而喻了
二、commons-fileupload:
官方網(wǎng)站:[http://jakarta.apache.org/commons/fileupload/]
它提供基于Servlet的上傳,可上傳到內(nèi)存、文件,且文件的上傳位置,最大上傳文件字節(jié)數(shù)可以在程序中設(shè)置,
特別是對(duì)于多文件上傳支持較好,List items = upload.parseRequest(request)就可以處理多文件,其他都不用考慮,
提供了item.isFormField()判斷是否為標(biāo)準(zhǔn)表單值的方法,簡(jiǎn)潔實(shí)用,但是可配置仍然不好,對(duì)API的依賴(lài)性很大
使用步驟:
1、首先判斷一個(gè)HttpServletRequest是否是一個(gè)上傳文件的請(qǐng)求:
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
2、處理請(qǐng)求:
2.1、創(chuàng)建基于硬盤(pán)存儲(chǔ)的工廠(chǎng)
DiskFileItemFactory factory = new DiskFileItemFactory();
/* 或者
DiskFileItemFactory factory = new DiskFileItemFactory(yourMaxMemorySize, yourTempDirectory);
*/
2.2、設(shè)置工廠(chǎng)屬性,從而生成個(gè)性化ServletFileUpload
//設(shè)置最多只允許在內(nèi)存中存儲(chǔ)的數(shù)據(jù),單位:字節(jié)
factory.setSizeThreshold(yourMaxMemorySize);
// 設(shè)置一旦文件大小超過(guò)getSizeThreshold()的值時(shí)數(shù)據(jù)存放在硬盤(pán)的目錄
factory.setRepository(yourTempDirectory);
2、處理上傳文件:
Iterator iter = items.iterator();
while (iter.hasNext()) {
?? FileItem item = (FileItem) iter.next();
?? //判斷是否為標(biāo)準(zhǔn)表單域
?? if (item.isFormField()) {
??????? String name = item.getFieldName();
?String value = item.getString();
???…
??? ?} else {
??String fieldname = item.getFieldName();
??String filename = item.getName();
??String contentType = item.getContentType();
??boolean isInMemory = item.isInMemory();
??long sizeInBytes = item.getSize();
??…
?//直接從內(nèi)存訪(fǎng)問(wèn)上傳數(shù)據(jù)
?byte[] data = item.get();
???
?//采用流方式讀取上傳文件
?InputStream stream = item.openStream();
?// 保存到文件
?if (writeToFile) {
?File uploadedFile = new File(storeFilePath);
?item.write(uploadedFile);
??? } else {
?//轉(zhuǎn)換為輸出流
?InputStream uploadedStream = item.getInputStream();
?...
?uploadedStream.close();
?}
}
...
三、javazoom的UploadBean:
官方網(wǎng)站:[http://www.javazoom.net/jzservlets/uploadbean/uploadbean.html]
功能強(qiáng)大,支持上傳到文件系統(tǒng),數(shù)據(jù)庫(kù),同時(shí)它還有一些高級(jí)功能,如對(duì)上傳的監(jiān)聽(tīng),overwrite過(guò)濾器、自定義解析器、
overwrite策略、黑名單、白名單等,特別是它采用了JavaBean方式,所以在JSP頁(yè)面可以輕松的采用
從而實(shí)現(xiàn)上傳到硬盤(pán)目錄但是它的源代碼是需要Money的,我們只能得到它的jar包和API Doc,
同時(shí)它對(duì)多文件上傳處理的不是很好(我覺(jué)得)。
官方網(wǎng)站上有詳細(xì)的說(shuō)明供參考。
四、Jspsmartupload
官方網(wǎng)站:[http://www.jspsmart.com/] 可惜一直打不開(kāi)
這里有一篇文章說(shuō)明:[http://java.ccidnet.com/art/3737/20060717/638255_1.html]