2010-04-07 56 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