How do I pass additional info with <input type=“file” >?

荒凉一梦 提交于 2019-12-13 15:44:15

问题


I need to upload files to a servlet running on tomcat. In addition to the file, I want to allow the user to add a comment associated with the file uploaded. I tried the following but it did not work:

<form action='MyUploadServlet' enctype='multipart/form-data' method='POST'>
    <input type='file' name='filechooser'><br />
    <textarea name='comment' cols='15' rows='5'></textarea>
    <input type='Submit' value='Upload'><br />
</form>

Here is a snippet from the server side code:

@WebServlet("/MyUploadServlet") 
public class MyUploadServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
            ServletContext sc = request.getServletContext();
            String comment = (String)request.getParameter("comment");
            ....etc}

The omitted part of the server code deals with receiving the contents of uploaded file.

The request.getParameter("comment") line above returns null. I use several servlets and multiple forms in my app. In all other places, if I use request.getParameter("form-input-name"), I always get the value of the corresponding input field. This is the only exception, namely when the form has an input field of type "file".

How do I pass in a comment along with the file upload submit?


回答1:


You need to get the text field value by the same API as you used to get the content of the uploaded file.

You have specified the HTML form to send the data in multipart/form-data encoding instead of the standard application/x-www-form-urlencoded encoding. The multipart/form-data encoding is mandatory in order to send the file's content along with the form submit. However, the getParameter() method works in combination with application/x-www-form-urlencoded only.

A multipart/form-data request is usually to be parsed with a multipart/form-data parser such as the well known Apache Commons FileUpload, which is a de facto standard in this area. However, since Servlet 3.0 (which you seem to be actually using, given the presence of the also in Servlet 3.0 introduced @WebServlet annotation), there's a new getParts() method which allows you to extract the necessary submitted data using the standard methods without the need for Apache Commons FileUpload. It's however still only a bit more verbose than with Apache Commons FileUpload. You can find a concrete example of the both approaches in this answer: How to upload files to server using JSP/Servlet?



来源:https://stackoverflow.com/questions/8638210/how-do-i-pass-additional-info-with-input-type-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!