How to upload an image and save it in database? [duplicate]
Solution 1:
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.
Solution 2:
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.