9
votes

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.

2
I think it would be better to save the file to an upload directory and save the file path in the db insteadscott
thats what i was thinking as well, but the table i use will be deleted periodically, possibly once every week also there would not be a HUGE amount of entries because i only have to make the new ads maybe 3-5 times a week so thered be at most 10 entries per week..iCodeLikeImDrunk

2 Answers

11
votes

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 use request.getPart() in servlet's doPost() method to get the file as an InputStream. For a concrete code example, see also How to upload files to server using JSP/Servlet?

Then, to save this InputStream in the DB, just use PreparedStatement#setBinaryStream() on a BLOB/varbinary/bytea column or whatever column represents "binary data" in your favorite DB engine.

preparedStatement = connection.prepareStatement("INSERT INTO user (name, email, logo) VALUES (?, ?, ?)");
preparedStatement.setString(1, name);
preparedStatement.setString(2, email);
preparedStatement.setBinaryStream(3, logo);
// ...

You don't necessarily need to convert this InputStream to byte[], 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.

1
votes

You probably should not be storing an image in a database. The database is literally the most expensive place where you can store binary data. DB size will grow fast and querying cost is high. You might end up with non-scalable and barely efficient solution of image hosting.

Store it in separate resource server, like Amazon S3 or anywhere else (local Nginx, Tomcat etc).

Instead you can store unique file names and/or full path to the file. In such a way you'll facilitate DB's workload and columns data will be readable, so you can quickly find desired picture. I'm not even talking about performance in general, simple benchmark will easily prove it.