星期四, 7月 06, 2006

Apache Commons(UploadFile)備忘記

以前一向以 JspSmartUpload 或 Oreilly MultiPartRequest 上載文件到伺服器.
今次使用 Apache Commons FileUpload .


首先下載 commons-fileupload-1.1.1.zip
http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi
下載後將 commons-fileupload-1.1.1.jar 放進 Project_name/WEB-INF/lib 裡.

下載 commons-io-1.2.zip :
http://jakarta.apache.org/site/downloads/downloads_commons-io.cgi
如果沒有下載這個library,會出現下面這個Exception,這個花了我不了的時間找.
java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream


UploadExcel.java
public class UploadExcel{
String tempDirectory = "/web_project_path/excel/temp/"; // 設定暫存目錄
String fileDirectory = "/web_project_path/fileupload/"; // 設定上存檔案目錄
String fileExtention = ".xls";

public UploadExcel() {}


public int uploadFile(HttpServletRequest request) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory(); // 建立factory
factory.setSizeThreshold(4000); // 設定緩存大小
factory.setRepository(new File(tempDirectory));  // 設定暫存Directory
ServletFileUpload upload = new ServletFileUpload(factory); // 建立Servlet File
upload.setSizeMax(1000000); // 設定上存檔案最大容量

List items = upload.parseRequest(request);
Iterator iter = items.iterator();

while (iter.hasNext()) { // 這裡lookup所有上存檔案
FileItem item = (FileItem) iter.next();


//if (item.isFormField()) {
// String name = item.getFieldName(); // 這裡取得parameter的名字
// String value = item.getString(); // 取得parameter的數值
//}
if (!item.isFormField()) {
String fieldName = item.getFieldName();
String fileName = item.getName();
// String contentType = item.getContentType();
// boolean isInMemory = item.isInMemory();
// long sizeInBytes = item.getSize();
if(!fileName.endsWith(fileExtention)) continue; //這裡亦可使用contentType來判斷
File uploadedFile = new File(fileDirectory + fieldName
+ ".xls");
item.write(uploadedFile); //將檔案寫到上存目錄
}
}


} catch (Exception e) {
System.out.println("Exception (UploadExcel): " + e);
return -1;
}
return 1;
}


}



uploadexcel.jsp
<jsp:useBean id="myUpload" scope="page" class="com.excel.UploadExcel" />


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title>Upload Excel</title>
</head>
<body>


<%
int iError = 1;
if (request.getParameter("action") != null
&& request.getParameter("action").equals("upload")) { // 判斷是否上存
iError = myUpload.uploadFile(request);
if(iError > 0){
out.println("<script>alert('Success');</script>");
} else {
out.println("<script>alert('Fail');</script>");
}
}


%>
<script type="text/javascript">
function openPopUp(){
self.location = 'excelDownload.jsp';
window.open(self.location,'openWin','');
}
function uploadsave(){
obj = document.formfile;
document.formfile.action='uploadexcel.jsp?action=upload';
document.formfile.submit();
}
</script>


<form name="formfile" method="post" enctype="multipart/form-data">
Please select file(Chinese)
<input type="file" name="excel_ch">
<br>
<input type="button" name="preview" value="Preview Excel" onclick="openPopUp();">
<input type="button" value="Upload" onclick="uploadsave();">
</form>
</body>
</html>



excelDownload.jsp
<%@ page import="java.io.*" %><%
response.setHeader("Content-disposition","attachment; filename=excel_ch.xls");
FileInputStream fis=new FileInputStream("/web_project_path/fileupload/excel_ch.xls");
OutputStream os=response.getOutputStream();
int byteRead;
while(-1 != (byteRead = fis.read())) {
os.write(byteRead);
}
os.close();
if (fis != null)
fis.close();
%>



以下是一些官方的教學:
http://jakarta.apache.org/commons/fileupload/using.html
http://jakarta.apache.org/commons/fileupload/faq.html








沒有留言: