Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Convert file to blob Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Convert file to blob" Watch "Convert file to blob" New topic
Author

Convert file to blob

Ivan Kesic
Ranch Hand

Joined: Feb 05, 2009
Posts: 68
I have a file chooser. And he returns File object. I need to store that object in my-sql so i need to convert it somehow to Blob object becouse that is the object preparedstatement needs . How do i do that? Normal casting doesn't work...

edit: I see that Blob is actually interface. Now im eaven more confused...
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4420
    
    8

Note that a File object just represents the location of the file. So casting is never going to work - the most you can expect to get from it directly would be the filename or path. But you can read from a file by creating a FileInputStream.

And if you look at PreparedStatement there's another method that should work, that takes an InputStream as an argument: setBinaryStream.

Any use?
Ivan Kesic
Ranch Hand

Joined: Feb 05, 2009
Posts: 68
Ok i did that, and its working. Thank you
edit: but i still have a problem. Now i get an exception, that data of an jpg is too long for column in sql. I just made FileInputStream object of file and past it in prepared statement. Why do i get this error?
java.io.FileInputStream@15ad5c6 this is my inputStream, and it needs i think to be smaller, not by size but this text as i figure. But i cant change this...

I fixed it. Just needed to set blob to be longblob, with java everything was fine...

Thank you
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Convert file to blob