0

I have a model Entity Image.
Entity has a field of type: Blob.
To perform file-uploads, use Apache Commons FileUpload Library.
To get my file, i use following code:

    Image image = new Image();
    ServletFileUpload upload = new ServletFileUpload();
    try {
        FileItemIterator itr = upload.getItemIterator(req);
        while(itr.hasNext()){
            FileItemStream item = itr.next();

            if(!item.isFormField())
            {
                image.setImageType(item.getContentType());
                InputStream stream = item.openStream();
                image.setImageData(???); //How to Set Blob Data from Input Stream
            }
        }
    } catch (FileUploadException e) {
        resp.sendError(500);
    }

Thanks.

Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
Vikas Raturi
  • 916
  • 2
  • 13
  • 23

1 Answers1

0

Use the Streams.copy(input, output, doClose) utility method that comes with Apache Commons FileUpload to copy the InputStream into a byte array and create a Blob from that:

InputStream stream = ...
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Streams.copy(stream, bytes, true /* close stream after copy */);
Blob blob = new Blob(bytes.toByteArray());
image.setImageData(blob);
Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65