简体   繁体   中英

Java JPA retrieve blob from oracle database as its original file type

I am using java spring and jpa I have a query to retrieve the blob from an oracle db. I get the blob and if it is a text file it is downloading onto my local machine just fine - but if it is an image I have to go through a BufferedImage, and I am still working on PDF. So far I'm just seeing the extension of the file by getting it's original filename which is also stored in the DB, then filtering the string for the extension. When I get a PDF it says the file is corrupted or open in another window, which it is not. So far, this is my code that tries to turn blob from DB into a file:

  Blob blob = Service.retrieveBlob(ID);
    if (blob == null){
      return false;
    }
    String fileName = Service.getFileName(ID);
    String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
    System.out.println(extension);
    if (extension.equals("jpg") || (extension.equals("png"))){
      File file = new File("./DBPicture.png");
      try(FileOutputStream outputStream = new FileOutputStream(file)) {
        BufferedImage bufferedImage = ImageIO.read(blob.getBinaryStream());
        ImageIO.write(bufferedImage, "png", outputStream);
        System.out.println("Image file location: "+file.getCanonicalPath());
      } catch (IOException e) {
        e.printStackTrace();
      }
}
    else {
      InputStream ins = blob.getBinaryStream();
      byte[] buffer = new byte[ins.available()];
      ins.read(buffer);

      File targetFile = new File("./" + fileName);
      OutputStream outStream = new FileOutputStream(targetFile);
      outStream.write(buffer);
}

available is simply that. it is not necessarily the length of the stream.

Try something like

InputStream ins = blob.getBinaryStream();
File targetFile = new File("./" + fileName);
OutputStream outStream = new FileOutputStream(targetFile);

byte[] buffer = new byte[8000];
int count = 0;
while ((count = ins.read(buffer)) != -1) {
    outStream.write(buffer);
}

// then close your output
outStream.close (); 

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