【问题标题】:Java JPA retrieve blob from oracle database as its original file typeJava JPA 从 oracle 数据库中检索 blob 作为其原始文件类型
【发布时间】:2020-02-12 17:52:24
【问题描述】:

我正在使用 java spring 和 jpa 我有一个查询来从 oracle db 中检索 blob。我得到了 blob,如果它是一个文本文件,它正在下载到我的本地机器上就好了 - 但如果它是一个图像,我必须通过一个 BufferedImage,我仍在处理 PDF。到目前为止,我只是通过获取文件的原始文件名来查看文件的扩展名,该文件名也存储在数据库中,然后过滤扩展名的字符串。当我收到 PDF 时,它说文件已损坏或在另一个窗口中打开,但事实并非如此。 到目前为止,这是我试图将 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);
}

【问题讨论】:

  • 请调试您的代码以准确显示您遇到的错误以及您拥有的数据。

标签: java spring oracle jpa blob


【解决方案1】:

available 就是这样。不一定是流的长度。

试试类似的东西

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 (); 

【讨论】:

  • 非常感谢,这对我有用。只是想知道,8000的大小合适吗?有没有办法让我找到要通过的 blob 的大小而不是 8000?
  • 我只是将 blob.length() 类型转换为 int 并使用它而不是 8000,还没有引发任何问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2016-05-28
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
相关资源
最近更新 更多