3

In Java JSP, I'm using input stream and BLOB datatype to write any type of file into the database. I want to retrieve the BLOB file. How should I go about retrieving it? I tried using select statement and got this (material column). enter image description here

UrsinusTheStrong
  • 1,239
  • 1
  • 16
  • 33
  • 1
    can you show some code, how you are inserting into the database ? – no one May 13 '16 at 17:12
  • 1
    [link](http://stackoverflow.com/questions/37203046/retrieving-file-upload-from-database) check the code –  May 13 '16 at 17:53

2 Answers2

2

Using a ResultSet, you can retrieve a java.sql.Blob instance:

Blob blob = resultSet.getBlob("MATERIAL");

Then you can open an input stream:

InputStream input = blob.getBinaryStream();

And write it to a file as described in Is it possible to create a File object from InputStream

Community
  • 1
  • 1
andrucz
  • 1,971
  • 2
  • 18
  • 30
  • 1
    how to show that input stream in jsp,after retrieving the value of blob material? –  May 13 '16 at 19:40
  • do you have to show it or be able to download it? what do you want to do if the file can't be showed? – andrucz May 16 '16 at 18:29
  • i solved this without using blob, for downloads igave the filepath and it works –  May 18 '16 at 10:16
0

Getting the Blob from the table:

try (ResultSet rs = statement.executeQuery(query)) {
    if(rs.next()) {
        fileBlob = rs.getBlob(1);
    }
}

Saving the contents of the Blob into a new file:

try (InputStream ipStream = fileBlob.getBinaryStream(1, fileBlob.length());
        OutputStream opStream = new FileOutputStream(new File("path/to/file"))) {                        
    int c;
    while ((c = ipStream.read()) > -1) {
        opStream.write(c);
    }
}
UrsinusTheStrong
  • 1,239
  • 1
  • 16
  • 33