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.