Search code examples
javadatabaseservletsjpajava-ee-6

How can I store BLOB in DB from Servlet using JPA


I am trying to write simple webapp using JSP / Servlet / EJB (for JPA) for uploading files (up to 50 mb) to DB.

In my entity class (User) i have following code:

@Lob
private byte[]             file;

Here is how I retrieve file in Servlet (actually it saves file on my computer and I want to change it):

for (Part part : request.getParts()) {
        InputStream is = request.getPart(part.getName()).getInputStream();
        int i = is.available();
        byte[] b = new byte[i];
        is.read(b);
        String fileName = getFileName(part);
        FileOutputStream os = new FileOutputStream("C:/files/" + fileName);
        os.write(b);
        is.close();
} 

I don't know how to write byte arrays (using for loop) to my User entity. Any ideas ?


Solution

  • Your input stream processing is incorrect - the available method doesn't return you the length of the entire stream, it only gives you the (estimated) amount that is available to be read before the stream will be blocked. Emphasis on estimate. You need to loop through reading the entire stream until a read call results in -1, or use a utility like IOUtils from Apache Commons IO.

    final byte[] data = IOUtils.toByteArray(inputStream);
    

    Once you have the data, just set it to your entity:

    entity.setFile(data);
    

    And then save it.