jsp上傳
用commons組件實現上傳
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%
DiskFileUpload dfu = new DiskFileUpload();
// 設置允許用戶上傳文件大小,單位:字節
dfu.setSizeMax(10000000);
// 設置最多只允許在內存中存儲的數據,單位:字節
dfu.setSizeThreshold(4096);
// 設置一個文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
//String strURL = new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
String xiangmumingcheng = (String) session.getAttribute("xiangmumingcheng");
String f_gonggao = "image"; //設定文件夾名稱
String m_path = request.getRealPath("/") + f_gonggao + "\\";
java.io.File r_path = new java.io.File(m_path);
if (!r_path.exists()) {
r_path.mkdir();
}
String strURL = m_path;
// System.out.println("路徑名" + strURL);
dfu.setRepositoryPath(strURL);
//開始讀取上傳信息
try {
List fileItems = dfu.parseRequest(request);
//依次處理每個上傳的文件
Iterator i = fileItems.iterator();
String n a m e = null;//這里的n a m e其實是name 但是在博客里不正常顯示所以就這么寫了
long size = 0;
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
//忽略其他不是文件域的所有表單信息
if (!fi.isFormField()) {
name = fi.getName();
size = fi.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
}
>
size = fi.getSize();
name = name.replace(':', '_');
name = name.replace('\\', '_');
File writeFile = new File(strURL, name);
String shangchuanlujing = f_gonggao + "\\" + name;
//System.out.println("上傳路徑" + shangchuanlujing);
fi.write(writeFile);
}
} catch (FileUploadException fue){
fue.printStackTrace();
//response.sendRedirect("ErrorPage.jsp");
}
%>
posted on 2007-07-20 22:50 hugh 閱讀(271) 評論(0) 編輯 收藏 所屬分類: JAVA