2009年7月15日 星期三

JSP+MultiPartRequest實作FileUpload

JSP要實作檔案上傳的方法很多,例如:jspSmart/O'Reilly/Jakarta等等,不過小弟找不到jspSmart的官網,在此以O'Reilly所提供的API為例:
1.先到http://www.servlets.com/cos/index.html下載套件(cos-26Dec2008.zip)
2.將ZIP檔unzip,然後將lib資料夾全都COPY到Web應用程式的WEB-INF下
3.先撰寫一個fileUpload.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>

<h1>Hello World!</h1>
<form action="implementUpLoad.jsp" method="POST" enctype="multipart/form-data">
<input type="file" name="files" value="" width="20" />
<input type="hidden" name="fileupload" value="go" /><br>
<input type="submit" value="Upload" />
</form>

</body>
</html>

注意:<form>中一定要加enctype="multipart/form-data"
4.再選寫一個implementUpLoad.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8" import="com.oreilly.servlet.MultipartRequest" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%
try {
String saveDirectory = "C:\\htdocs\\JSP\\jsp\\web\\files\\";
int maxPostSize = 5 * 1024 * 1024;
MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "UTF-8");

//MultipartRequest m=new MutipartRequest();
out.println(multi.getFileNames().nextElement());
out.println(multi.getFilesystemName((String)multi.getFileNames().nextElement()));
} catch (Exception e) {
out.println(e.getMessage());
}
%>
</body>
</html>

資料來源:http://caterpillar.onlyfun.net/Gossip/JSPServlet/FileUpload.htm

沒有留言: