練功房推薦書單

  • 猛虎出柙雙劍合璧版--最新 OCA / OCP Java SE 7 Programmer 專業認證 (電子書)
  • 流浪教師存零股存到3000萬(全新增修版)(書+DVD)
  • 開始在關西自助旅行(京都‧大阪‧神戶‧奈良)(全新增訂版)
  • 不敗教主的300張股票存股術

JSP精選實用範例(二):檔案上傳 RSS feed
Forum Index » 網頁程式設計 Web Development
Author Message
andowson

七段學員
[Avatar]

Joined: 2007/1/2
Messages: 710
Location: 台北
Offline
如果要讓上傳後的檔案名稱可以另外指定的話,我們需要加上一個新的欄位filename在表單的最前面(因為是系統是依序處理的)
fileupload_streaming.html:

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

檔案上傳



<form name="upload" enctype="multipart/form-data" method="post" action="fileupload_streaming.jsp">

存檔名稱: <input type="text" name="filename" size="50" maxlength="255">


上傳檔案: <input type="file" name="file" size="20" maxlength="20">


檔案說明: <input type="text" name="filedesc" size="30" maxlength="50">


<input type="submit"value="上傳"> <input type="reset" value="清除">


</form>
存檔名稱:伺服器上儲存之檔案名稱(空白表示與上傳檔案名稱相同)

檔案說明:請描述該檔案的內容

</body>
</html>

在處理表單資料時,我們需要另外宣告一個filenameSaved字串變數放在while迴圈外面,初始值設為null,等到while迴圈內部讀取到filename這個欄位名稱時將value的值設定給它。
接下來處理到file型態的表單資料時,再比對上傳的檔案名稱和我們的存檔名稱是否相同,若有設定新的存檔名稱時,將fileName變數的值改為我們設定的filenameSaved。下面就照原來的邏輯去處理即可。

fileupload_streaming.jsp:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="java.io.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.util.Streams"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>
<%
String saveDirectory = application.getRealPath("/upload");
// Change save direcoty to another place outside of Tomcat
//String saveDirectory = "C:/upload";
File dir = new File(saveDirectory);
if (!dir.exists()) {
boolean success = dir.mkdir();
if (success) {
System.out.println("Directory: " + saveDirectory + " created");
}
}

out.println("file.encoding=" + System.getProperty("file.encoding") + "<br>");

// Solve Chinese filename problem: use original form encoding
String encoding = "UTF-8";
request.setCharacterEncoding(encoding);

// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
out.println("isMultipart=" + isMultipart + "<br>");

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();

//Create a progress listener
ProgressListener progressListener = new ProgressListener(){
private long megaBytes = -1;
public void update(long pBytesRead, long pContentLength, int pItems) {
long mBytes = pBytesRead / 1000000;
if (megaBytes == mBytes) {
return;
}
megaBytes = mBytes;
System.out.println("We are currently reading item " + pItems);
if (pContentLength == -1) {
System.out.println("So far, " + pBytesRead + " bytes have been read.");
} else {
System.out.println("So far, " + pBytesRead + " of " + pContentLength
+ " bytes have been read.");
}
}
};
upload.setProgressListener(progressListener);

// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
String filenameSaved = null;
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
String value = Streams.asString(stream, encoding);
out.println(name + "=" + value + "<br>");
if ("filename".equals(name)) {
filenameSaved = value;
System.out.println(name + "=" + value);
}
} else {
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
// Process the input stream
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
out.println("fieldName=" + fieldName + "<br>");
out.println("fileName=" + fileName + "<br>");
out.println("contentType=" + contentType + "<br>");
if (fileName != null && !"".equals(fileName)) {
fileName = FilenameUtils.getName(fileName);
if (filenameSaved != null && !"".equals(filenameSaved) && !filenameSaved.equals(fileName)) {
fileName = filenameSaved;
}
out.println("fileName saved=" + fileName + "<br>");
File uploadedFile = new File(saveDirectory, fileName);
FileOutputStream uploadedFileStream =
new FileOutputStream(uploadedFile);
Streams.copy(stream, uploadedFileStream, true);
}
}
}
%>
<input type="button" name="prev" value="Go back to previous page" onclick="history.go(-1);"/>

檔案說明這欄是當您想要將這些表單資料儲存到資料庫時才有用。

回上頁的按鈕可以加在最底下:
<input type="button" name="prev" value="Go back to previous page" onclick="history.go(-1);"/>
 Filename fileupload_streaming.jsp [Disk] Download
 Description fileupload_streaming.jsp with new filename saved processing
 Filesize 4 Kbytes
 Downloaded:  12 time(s)

 Filename fileupload_streaming.html [Disk] Download
 Description fileupload_streaming.html with new filename saved
 Filesize 803 bytes
 Downloaded:  8 time(s)


分享經驗 累積智慧
[WWW]
hero9

十級學員

Joined: 2012/8/23
Messages: 2
Offline
請問大大:

可以夾帶資料過去嗎

就是我要在第1頁session

可是下一頁就是抓不到

該如何解決
andowson

七段學員
[Avatar]

Joined: 2007/1/2
Messages: 710
Location: 台北
Offline
hero9您好:
請把您在程式哪裡加上session,然後怎麼取出session指出一下。
(請附上您的程式碼方便了解您的問題所在)

分享經驗 累積智慧
[WWW]
hero9

十級學員

Joined: 2012/8/23
Messages: 2
Offline
andowson大大:

我有試過把 form 裡的 enctype="multipart/form-data" 拿掉

這樣的話我想取的值是取得到的,但這樣就無法上傳了(只是測試)

1.也有試過讓 form 裡的 action 到本頁,最後再用 javascript 到下一頁去

2.最後想說讓值先到 hidden 裡,然後下一頁再用 request.getParameter 去接

兩者都行不通

下一頁我有打

String sd = (String)session.getAttribute("sd");
out.println(sd);

sd顯示是null
 Filename text.jsp [Disk] Download
 Description 這是第1頁的,第2頁則是fileupload.jsp
 Filesize 2 Kbytes
 Downloaded:  2 time(s)

andowson

七段學員
[Avatar]

Joined: 2007/1/2
Messages: 710
Location: 台北
Offline
hero9您好:
可否請您說清楚您的網頁流程,例如
text.jsp->fileupload.jsp->next.jsp
text.jsp會傳兩個參數file1(file型態), sd(select型態)給fileupload.jsp
在fileupload.jsp會取出file1及sd的值, 並將sd的值設定到session變數sd去。
然後由next.jsp再取出session變數sd的值?

分享經驗 累積智慧
[WWW]
sweetxuite

十級學員

Joined: 2013/1/3
Messages: 1
Offline
你好

請問我現在要傳到別人的server

我下載您的範例檔已經上傳到他主機的ftp內

然後用他的主機開上傳網頁 按下上傳之後出現

org.apache.jasper.JasperException: An exception occurred processing JSP page /stu/csie101/14994046/testjsp/fileupload.jsp at line 74

java.io.FileNotFoundException: D:\AppServ\Tomcat 6.0\webapps\ROOT\images\05_45_3_web.jpg (系統找不到指定的路徑。)

他找不到路徑 可是我上傳到FTP資料夾的裡面有建upload資料夾


---------FTP資料夾
upload->資料夾
fileupload.jsp
fileupload.html

---------

這樣怎麼解決呢





andowson

七段學員
[Avatar]

Joined: 2007/1/2
Messages: 710
Location: 台北
Offline
sweetxuite 你好,

請問這部Server是否為Linux或UNIX-like系統,因為看起來檔案路徑是長這樣
/stu/csie101/14994046/testjsp/fileupload.jsp

又就錯誤訊息看起來是指定了一個Windows上面的檔案路徑:
D:\AppServ\Tomcat 6.0\webapps\ROOT\images\05_45_3_web.jpg (系統找不到指定的路徑。)

所以可能要請您確認一下fileupload.jsp的內容是否有修改過,另一種是去找出Server上Tomcat自動轉譯產生的中間原始檔fileupload_jsp.java的內容確認一下第74行的內容為何。

分享經驗 累積智慧
[WWW]
初心者

十級學員

Joined: 2015/9/20
Messages: 3
Offline
上傳已經成功了 感謝!

可是,傳到build裡面,圖片抓不出來,請問該怎麼解決???
初心者

十級學員

Joined: 2015/9/20
Messages: 3
Offline
初心者 wrote:上傳已經成功了 感謝!

可是,傳到build裡面,圖片抓不出來,請問該怎麼解決???


<img src="./build/web/images/<%= fileName%>.jpg" width="100px" height="156px">
  • [Thumb - 未命名.png]
 Filename 未命名.png [Disk] Download
 Description No description given
 Filesize 22 Kbytes
 Downloaded:  0 time(s)

andowson

七段學員
[Avatar]

Joined: 2007/1/2
Messages: 710
Location: 台北
Offline
初心者您好:
依我初步的了解,您應該是使用NetBeans IDE作為開發環境,build這個目錄傳統上應該是IDE環境自動產生,用來放置編譯後程式的地方,所以不應該將build列入您的路徑上。
建議您將檔案上傳到web/images目錄下,然後將圖片的路徑改為下面這樣測試看看:

<img src="/web/images/<%= fileName%>.jpg" width="100px" height="156px">

分享經驗 累積智慧
[WWW]
初心者

十級學員

Joined: 2015/9/20
Messages: 3
Offline
你好,已經可以抓得到照片了感謝你~

但我現在遇到一個問題是 我要把regular form field 寫入到資料庫中

我是這樣子寫的

String fileName = null;
String value = null;
String v2 = null;
String v3 = null;
String v4 = null;
String v5 = null;
String v6 = null;

while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

if (item.isFormField()) {
// Process a regular form field
//processFormField(item);
String name = item.getFieldName();
value = item.getString();
String n2 = item.getFieldName();
v2 = item.getString();
String n3 = item.getFieldName();
v3 = item.getString();
String n4 = item.getFieldName();
v4 = item.getString();
String n5 = item.getFieldName();
v5 = item.getString();
String n6 = item.getFieldName();
v6 = item.getString();
value = new String(value.getBytes("UTF-8"), "ISO-8859-1");
v2 = new String(value.getBytes("UTF-8"), "ISO-8859-1");
v3 = new String(value.getBytes("UTF-8"), "ISO-8859-1");
v4 = new String(value.getBytes("UTF-8"), "ISO-8859-1");
v5 = new String(value.getBytes("UTF-8"), "ISO-8859-1");
v6 = new String(value.getBytes("UTF-8"), "ISO-8859-1");


但是我存入的時候 會是亂碼, 而且中文似乎沒辦法
andowson

七段學員
[Avatar]

Joined: 2007/1/2
Messages: 710
Location: 台北
Offline
初心者您好:
您可以參考這篇的#27號回應相關說明
http://www.andowson.com/posts/list/15/197.page

分享經驗 累積智慧
[WWW]
dream1978

十級學員

Joined: 2017/5/27
Messages: 5
Offline
版大:
我用你提供的範本檔案來執行,但是有些問題!!!
我是用Eclipse + JBoos-4.0.5.GA + jdk1.6.0_41

程式中我有多加下列兩行,建立目錄用的
File mkupload = new File(saveDirectory);
mkupload.mkdir();

請問一下,我是那個部分沒有注意到的嗎?

錯誤訊息如下:
exception

org.apache.jasper.JasperException: Exception in JSP: /fileupload.jsp:48

45: upload.setProgressListener(progressListener);
46:
47: // Parse the request
48: List items = upload.parseRequest(request);
49:
50: // Process the uploaded items
51:


Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:506)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)


root cause

javax.servlet.ServletException: Bad version number in .class file
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:843)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:776)
org.apache.jsp.fileupload_jsp._jspService(fileupload_jsp.java:140)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:334)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)


root cause

java.lang.UnsupportedClassVersionError: Bad version number in .class file
java.lang.ClassLoader.defineClass1(Native Method)
java.lang.ClassLoader.defineClass(Unknown Source)
java.security.SecureClassLoader.defineClass(Unknown Source)
org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1815)
org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:869)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1322)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1201)
java.lang.ClassLoader.loadClassInternal(Unknown Source)
org.apache.commons.fileupload.util.Streams.copy(Streams.java:123)
org.apache.commons.fileupload.util.Streams.copy(Streams.java:70)
org.apache.commons.fileupload.MultipartStream.readBodyData(MultipartStream.java:593)
org.apache.commons.fileupload.MultipartStream.discardBodyData(MultipartStream.java:617)
org.apache.commons.fileupload.MultipartStream.skipPreamble(MultipartStream.java:634)
org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:1023)
org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:1003)
org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:310)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:334)
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
org.apache.jsp.fileupload_jsp._jspService(fileupload_jsp.java:96)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:334)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)


note The full stack trace of the root cause is available in the Apache Tomcat/5.5.20 logs.


 Filename fileupload.html [Disk] Download
 Description No description given
 Filesize 543 bytes
 Downloaded:  0 time(s)

 Filename fileupload.jsp [Disk] Download
 Description No description given
 Filesize 3 Kbytes
 Downloaded:  2 time(s)

andowson

七段學員
[Avatar]

Joined: 2007/1/2
Messages: 710
Location: 台北
Offline
dream1978您好:
你的主要問題原因是這一行:
java.lang.UnsupportedClassVersionError: Bad version number in .class file

請檢查Eclipse中的Java compiler設定是哪個版本的JDK

分享經驗 累積智慧
[WWW]
dream1978

十級學員

Joined: 2017/5/27
Messages: 5
Offline
andowson wrote:dream1978您好:
你的主要問題原因是這一行:
java.lang.UnsupportedClassVersionError: Bad version number in .class file

請檢查Eclipse中的Java compiler設定是哪個版本的JDK


有1.5、1.6我都試過,都是一樣的結果
請問大大是否要新的版本才支援?如果是新版才支援的話,那是否1.5或是1.6有支援的寫法呢?
 
Forum Index » 網頁程式設計 Web Development
Go to:   
Mobile view