2010-04-07 50 views
3

獲得input type="file" (由用戶在文件對話框中選擇的條目)如何在JSP

<script> 
    function OpenFileDialog(form) {  
     var a = document.getElementById("inputfile").click(); 
     SampleForm.filePath.value = //set the path here 
     document.SampleForm.submit(); 
    } 
</script> 

<form name="SampleForm" action="TestServlet" method="get"> 
    <input type="file" style="display:none;" id="inputfile"/> 
    <a href="javascript:OpenFileDialog(this.form);">Open here</a> 
    <input type="hidden" name="filePath" value=""/> 
</form> 

我的文件路徑希望在我的Servlet類中讀取所選文件的路徑 如何獲取文件路徑?我可以從var a讀取嗎? 或者有什麼方法可以直接從我的servlet中的input type="file"訪問文件路徑?

回答

9

首先調用的getParameter,要明確一個共同的誤解:文件的路徑是在服務器端毫無價值。想象一下,我是客戶,我給你的文件路徑c:/passwords.txt,你會如何作爲服務器獲得其內容?使用java.io.File?沒有?只有當客戶端和服務器運行在物理上相同的機器時,這纔會起作用。 只有可能的發生是當地的開發環境。

二,澄清限制:由於安全限制,JavaScript無法對input type="file"元素進行任何操作。如果有可能,那麼可以開發一個網站,將上傳的文件設置爲c:/passwords.txt,並在onload期間提交表單。這很容易,無憂地收集訪問該網站的所有人的所有密碼文件!沒有?

畢竟,你對文件的內容很感興趣。如HTML forms spec中所述,您需要將請求方法設置爲POST,並將請求編碼設置爲父代<form>元素中的multipart/form-data

<form action="upload" method="post" enctype="multipart/form-data"> 
    <input type="file" name="file"> 
    <input type="submit"> 
</form> 

這樣文件將在請求正文中發送。由於2.5以下的標準Servlet API版本沒有解析mulipart/form-data請求的內置工具,因此您需要自己解析請求。最好的方法是使用Apache Commons FileUpload。請按照鏈接閱讀用戶指南常見問題代碼示例和提示&技巧。當你已經在Servlet 3.0上時,你可以使用爲此提供的HttpServletRequest#getParts()提供的Servlet API。 You can find here an article with code examples about that

+0

感謝BalusC爲您的詳細說明.. :) 我是新來的,因此不理解訪問文件路徑的影響... 我想我需要使用Servlet到版本2.5,所以我會按照你提到的方法閱讀文件的內容... 再次感謝! – deepthinker121 2010-04-07 13:05:22

+0

不,servlet版本沒有限制。 2.5版本以前沒有內置的方法可以輕鬆解析上傳的文件。您需要獲取Apache Commons FileUpload。但是,如果您已經使用全新的3.0版本,那麼您可以使用內置的方式來解析上傳的文件。 – BalusC 2010-04-07 13:07:21

+0

好吧,明白了.. 我也想執行反向操作 - 從服務器下載文件 - 想要打開文件對話框來選擇下載位置......這怎麼辦? – deepthinker121 2010-04-07 17:52:38

0

(來自http://www.jguru.com/faq/view.jsp?EID=1045507兩者)​​

解決方案A:

  1. 下載http://www.servlets.com/cos/index.html
  2. 檢查http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartRequest.html - 它有相關的getter。

溶液B:

  1. 下載http://commons.apache.org/fileupload/
  2. 在 org.apache.commons.fileupload.MultipartStream調用readHeaders()

溶液C:

  1. 下載http://users.boone.net/wbrameld/multipartformdata/
  2. 上 com.bigfoot.bugar.servlet.http.MultipartFormData