简体   繁体   English

Java JPA 从 oracle 数据库中检索 blob 作为其原始文件类型

[英]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 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.我得到了 blob,如果它是一个文本文件,它正在下载到我的本地机器上就好了 - 但如果它是一个图像,我必须通过 BufferedImage 到 go,我仍在处理 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.当我收到 PDF 时,它说文件已损坏或在另一个 window 中打开,但事实并非如此。 So far, this is my code that tries to turn blob from DB into a file:到目前为止,这是我试图将 blob 从 DB 转换为文件的代码:

  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. available就是这样。 it is not necessarily the length of the stream.它不一定是 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 (); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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