简体   繁体   中英

How to save a picture in Java into Multiple blob?

As I described in the title, I tried to access a picture file several times using an InputStream , then save it to blob type database but the result is null for the second, third, and so on. Here is the snippet of the code:

File image1 = new File("src/template1.png").getAbsoluteFile();
File image2 = new File("src/template2.png").getAbsoluteFile();
InputStream in1 = new FileInputStream(image1);
InputStream in2 = new FileInputStream(image2);
long length1 = image1.length();
long length2 = image2.length();
pstmt.setString(1, jTextField18.getText().toUpperCase());
pstmt.setBlob( 2, in1, length1 );
pstmt.setBlob( 3, in1, length1 );
pstmt.setBlob( 4, in1, length1 );
pstmt.setBlob( 5, in1, length1 );
pstmt.setBlob( 6, in1, length1 );
pstmt.setBlob( 7, in2, length2 );
Pstmt.setBlob( 8, in2, length2 );

then the result is:

YR/21
[BLOB - 5.6 KiB]
[BLOB - 0 B]
[BLOB - 0 B]
[BLOB - 0 B]
[BLOB - 0 B]
[BLOB - 5.5 KiB]
[BLOB - 0 B]

I tried to use new InputStream like this code and another error occured. It says: Row size too large(>8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DINAMIC or ROW_FORMAT=COMPRESSED may help. In current row format, BLOB prefix of 768 bytes is stored inline.

pstmt.setBlob( 2, in1, length1 );
image1 = new File("src/template1.png").getAbsoluteFile();
in1 = new FileInputStream(image1);
pstmt.setBlob( 3, in1, length1 );
image1 = new File("src/template1.png").getAbsoluteFile();
in1 = new FileInputStream(image1);
pstmt.setBlob( 4, in1, length1 );

I think the problem is answered and change into another problem. Thanks for the answer

The first call consumes the stream, and the subsequent calls get no data. You need a separate InputStream for each call.

"Is there any way to save a picture to multiple blob?"

Yes, but your code will only work for small images. Instead, have a parent reference for the image and a children for the actual image, which will have the blobs. Make the children small and save only a chunk of the image to every one of them.

This will help you manage the space and it will be easier to back up.

For a reference on how to read a file in chunks, take a look here: http://www.javapractices.com/topic/TopicAction.do?Id=245

Save the chunk of the image to the database using the while-loop that reads the file.

It could be a lengthy operation to save the file, so you could have a flag on the parent defining if the children were all loaded or not. Thus preventing other threads from reading incomplete images.

If you are using MySQL, there's this tutorial on how to read and write images: http://zetcode.com/db/mysqljava/

Have fun.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM