How to convert multipartfile into Blob type
Asked Answered
A

3

6

Hi I am working with saving Image into DB,I am Taking Image as Multipart and trying to convert into Blob type. I do this method:

Blob blob=Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(multipartFile.getInputStream(),multipartFile.getSize());

But getting Nullpointer Exception While Executing. the file is Unable to convert multipart into Blob, any other Method to saving Image into DB.

Ancelin answered 6/8, 2013 at 7:3 Comment(0)
L
4
MultipartFile savedFile;
savedFile=itemView.getImgFile();//file from model attribute 
Blob blob=Hibernate.createBlob(savedFile.getInputStream()); // hibernate method for create blob 
//Save method will be call here 

http://viralpatel.net/blogs/tutorial-save-get-blob-object-spring-3-mvc-hibernate/ i followed above tutorial

Lefty answered 23/1, 2014 at 11:5 Comment(1)
I get this error The method createBlob(InputStream) is undefined for the type Hibernate when i use the createBlob() method, as it is deprecated and in Hibernate version 4..Filing
R
3

You can use this approach. Get multipart data and convert it into byte arrray and then convert to Blob

for (MultipartFile file : productsBean.getData()) {
    byte[] bytes = file.getBytes();
    Blob blob = new javax.sql.rowset.serial.SerialBlob(bytes);
    }

It's working for me :)

Robertaroberto answered 4/3, 2018 at 13:23 Comment(1)
This is not an efficient way as this loads whole data (byte array) into memory (RAM) from multipart object (which doesn't contain data but contains reference to data).Estienne
B
0

BlobProxy can be used.

import org.hibernate.engine.jdbc.BlobProxy;
// ...
Blob blob = BlobProxy.generateProxy(multipartFile.getInputStream(),
                                    multipartFile.getSize());
Beggar answered 2/1 at 21:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.