8

The form in the HTML is like

...
<form method="post" action="/foobar">
  <input type="file" name="attachment" />
  <input type="text" name="foo" />
  ... other input fields
</form>

And the Servlet will be like

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String attachment = request.getParameter("attachement");
    String foo = request.getParameter("foo");
    // get other parameters from the request
    // and get the attachment file
}

And I'm wondering

  1. Is there any ways that do not use 3rd-party libraries to get files from a HttpServletRequest object?

  2. What request.getParameter("attachement") returns? Is it the file name or something else?

  3. Would the binary input be stored automatically by a web container in file system or just in memory temporarily?

Wenhao Ji
  • 5,121
  • 7
  • 29
  • 40
  • 4
    Here you go: http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet/2424824#2424824 – Sotirios Delimanolis Mar 01 '13 at 15:32
  • You also might take a look at http://stackoverflow.com/questions/3831680/httpservletrequest-get-post-data it process JSON data. If your attachment is represented by an URL, you would need to HTTPURLConnection to fetch the data. – Alex M Mar 01 '13 at 15:38

2 Answers2

2

before anythging your form action should be "POST" and enctype="multipart/form-data".

that said...for you to get the file you must prepare the request yourself.

you should check:

Multipart requests/responses java

Community
  • 1
  • 1
Ricardo
  • 109
  • 3
0

add in your form enctype="multipart/form-data"

<form name="formname" action="servletName" method="post"  enctype="multipart/form-data">
<input type="file" name="attachment" />
  <input type="text" name="foo" />
  ... other input fields
</form>

now when you submit the form on the controller side you can get the picture by

String picture = (request.getParameter("attachment")).getBytes();

i have assumed the file to be a image , you can pass any file

  • 2
    Shouldn't you receive the file in a byte array instead of a String. Anyways its not even gonna compile. May be a typo from your end. – Manpreet Nov 11 '14 at 07:58