This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Your approach didn't work because you assumed that the only thing in the upload would be the contents of the file being uploaded. That is not the case.
The getInputStream() method provides an InputStream through which the servlet can read the contents of the HTTP request. That's what it's useful for. Of course if you don't understand how the request is structured, and you just guess, you aren't going to get satisfactory results. But that doesn't make the InputStream useless.
Use PUT? Well, that's just another guess on your part, isn't it? You'll find that the format of an HTTP file upload is documented in an RFC somewhere. If you really want to process a file upload with your own code then your first step should be to read that documentation.
Joined: Mar 25, 2010
Why I have <input type="file">? How can I use it? Could you give-me some example of code?
pedro abs wrote:Why I have <input type="file">? How can I use it? Could you give-me some example of code?
I don't understand. You already have an example of the HTML code for a file upload... it's in your question there. But maybe you meant to ask for an example of Java code to handle a file upload at the server? In which case you already have an example of that, too, namely the Apache code.
In other words I don't understand what your goal is.
The Servlet and JSP specs do not make any special provisions for multipart requests (file uploads).
Servlet and JSP developers either have to depend on third party libraries or make their own framework for this.
The two most popular are Jakarta Commons FileUpload and com.oreilly.servlet
The file upload form looks just like any other form except that:
the form tag must specify the POST method
the form tag must specify an enctype of multipart/form-data
the form must contain an <input type=file> element.
So, correcting your HTML code including the encoding type in the form:
Probably if you make this change, you will obtain more than 44 from request.getContentLength().
As already said, to process this request you should use a 3rd party library like the ones pointed out before. I'm used to use Commons-FileUpload. Works perfectly and has a complete documentation.
The field of type "file" together with the appropriate encoding type tells the browser to send the contents of the file in one of the parts of the request.
BTW, if you return the contents of a .jpg you should better write the appropriate headers... ;)