I have to create a form using JavaScript and an user will upload a JPG file and submit along with other info such as name, email, etc. When the user clicks submit all the information from the form will be loaded to a value object. For the image file I’ve set it to be byte[].
So assuming:
public String name;
public String email;
public byte[] logo;
I’ve set up a servlet as well to handle the submission but I’m not sure how to get started. How does the upload work? When user submits, how do I get the information for the image? Here’s a screenshot: http://imageshack.us/f/32/77675354.png/ I need to convert that image and save it to a byte[] then convert to blob so I can insert it to a table.
For the file upload part, you need to set
enctype="multipart/form-data"on the HTML form so that the webbrowser will send the file content and you’d like to userequest.getPart()in servlet’sdoPost()method to get the file as anInputStream. For a concrete code example, see also How to upload files to server using JSP/Servlet?Then, to save this
InputStreamin the DB, just usePreparedStatement#setBinaryStream()on aBLOB/varbinary/byteacolumn or whatever column represents “binary data” in your favorite DB engine.You don’t necessarily need to convert this
InputStreamtobyte[], it would not have been memory efficient either. Imagine that 100 user simultaneously upload images of 10MB, then 1GB of server memory would have been allocated at that point.