commons.fileupload實現(xiàn)文件的上傳,代碼如下:
<%!
//服務(wù)器端保存上傳文件的路徑
String saveDirectory = "g:\\upload\\";
// 臨時路徑 一旦文件大小超過getSizeThreshold()的值時數(shù)據(jù)存放在硬盤的目錄
String tmpDirectory = "g:\\upload\\tmp\\";
// 最多只允許在內(nèi)存中存儲的數(shù)據(jù)大小,單位:字節(jié)
int maxPostSize = 1024 * 1024;
%>
<%
// 文件內(nèi)容
String FileDescription = null;
// 文件名(包括路徑)
String FileName = null;
// 文件大小
long FileSize = 0;
// 文件類型
String ContentType = null;
%>
<%
DiskFileUpload fu = new DiskFileUpload();
// 設(shè)置允許用戶上傳文件大小,單位:字節(jié)
fu.setSizeMax(200*1024*1024);
// 設(shè)置最多只允許在內(nèi)存中存儲的數(shù)據(jù),單位:字節(jié)
fu.setSizeThreshold(maxPostSize);
// 設(shè)置一旦文件大小超過getSizeThreshold()的值時數(shù)據(jù)存放在硬盤的目錄
fu.setRepositoryPath("g:\\upload\\tmp\\");
//開始讀取上傳信息 得到所有文件
try{
List fileItems = fu.parseRequest(request);
}catch(FileUploadException e){
//這里異常產(chǎn)生的原因可能是用戶上傳文件超過限制、不明類型的文件等
//自己處理的代碼
}
%>
<%
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
String contentType = item.getContentType();
if((name==null||name.equals("")) && size==0)
continue;
%>
<%
//保存上傳的文件到指定的目錄
String[] names=StringUtils.split(name,"\\"); //對原來帶路徑的文件名進(jìn)行分割
name = names[names.length-1];
item.write(new File(saveDirectory+ name));
}
}
%>
下面是其簡單的使用場景:
A、上傳項目只要足夠小,就應(yīng)該保留在內(nèi)存里。
B、較大的項目應(yīng)該被寫在硬盤的臨時文件上。
C、非常大的上傳請求應(yīng)該避免。
D、限制項目在內(nèi)存中所占的空間,限制最大的上傳請求,并且設(shè)定臨時文件的位置。
可以根據(jù)具體使用用servlet來重寫,具體參數(shù)配置可以統(tǒng)一放置到一配置文件
文件的下載用servlet實現(xiàn) public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
String aFilePath = null; //要下載的文件路徑
String aFileName = null; //要下載的文件名
FileInputStream in = null; //輸入流
ServletOutputStream out = null; //輸出流
try
{
aFilePath = getFilePath(request);
aFileName = getFileName(request);
response.setContentType(getContentType(aFileName) + "; charset=UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + aFileName);
in = new FileInputStream(aFilePath + aFileName); //讀入文件
out = response.getOutputStream();
out.flush();
int aRead = 0;
while((aRead = in.read()) != -1 & in != null)
{
out.write(aRead);
}
out.flush();
}
catch(Throwable e)
{
log.error("FileDownload doGet() IO error!",e);
}
finally
{
try
{
in.close();
out.close();
}
catch(Throwable e)
{
log.error("FileDownload doGet() IO close error!",e);
}
}
}
http://m.tkk7.com/ronghao 榮浩原創(chuàng),轉(zhuǎn)載請注明出處:)
posted on 2005-12-16 10:46
ronghao 閱讀(6241)
評論(1) 編輯 收藏 所屬分類:
j2se基礎(chǔ)