How to get the file name for <input type=“file” in jsp

后端 未结 2 2039
悲&欢浪女
悲&欢浪女 2021-02-10 22:27

I want to read the file path from html input type=\"file\" (the entry selected in the file dialog by the user)



        
相关标签:
2条回答
  • 2021-02-10 23:05

    First, to clear a common misunderstanding: the file path is worthless in the server side. Imagine that I am the client and I give you the file path c:/passwords.txt, how would you as being the server ever get its contents? Using java.io.File? No? That would only work if both client and server runs at the physically same machine. The only possible occurence is the local development environment.

    Second, to clarify a restriction: Javascript cannot do anything with a input type="file" element due to security restrictions. If it was possible, then one could develop a website which sets the uploaded file to c:/passwords.txt and submits the form during onload. That's easy unaskingly collecting of all password files from everyone who visits the website! No?

    After all, you're rather interested in the file contents. As stated in the HTML forms spec you need to set the request method to POST and the request encoding to multipart/form-data in the parent <form> element.

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

    This way the file will be sent in the request body. As the standard Servlet API versions up to with 2.5 doesn't have builtin facilities to parse mulipart/form-data requests, you need to parse the request yourself. The best way is to use Apache Commons FileUpload for this. Follow the link and read both the User Guide and Frequently Asked Questions for code examples and tips&tricks. When you're already on Servlet 3.0, then you can just use the Servlet API provided HttpServletRequest#getParts() for this. You can find here an article with code examples about that.

    0 讨论(0)
  • 2021-02-10 23:09

    (Taken from http://www.jguru.com/faq/view.jsp?EID=1045507)

    Solution A:

    1. Download http://www.servlets.com/cos/index.html
    2. Check http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartRequest.html - it has the relevant getter.

    Solution B:

    1. download http://commons.apache.org/fileupload/
    2. invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

    Solution C:

    1. download http://users.boone.net/wbrameld/multipartformdata/
    2. invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData
    0 讨论(0)
提交回复
热议问题