How to convert Part to Blob, so I can store it in MySQL? It is an image. Thank you
My form
The SQL database BLOB type is in Java represented as byte[]
. This is in JPA further to be annotated as @Lob
. So, your model basically need to look like this:
@Entity
public class SomeEntity {
@Lob
private byte[] image;
// ...
}
As to dealing with Part
, you thus basically need to read its InputStream
into a byte[]
. Apache Commons IO IOUtils
is helpful here:
InputStream input = uploadedFile.getInputStream();
byte[] image = IOUtils.toByteArray(input); // Apache commons IO.
someEntity.setImage(image);
// ...
Or if you prefer standard Java API which is only a bit more verbose:
InputStream input = uploadedFile.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) output.write(buffer, 0, length);
someEntity.setImage(output.toByteArray());
// ...