簡體   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. 我得到了 blob,如果它是一個文本文件,它正在下載到我的本地機器上就好了 - 但如果它是一個圖像,我必須通過 BufferedImage 到 go,我仍在處理 PDF。 到目前為止,我只是通過獲取文件的原始文件名來查看文件的擴展名,該文件名也存儲在數據庫中,然后過濾擴展名的字符串。 當我收到 PDF 時,它說文件已損壞或在另一個 window 中打開,但事實並非如此。 到目前為止,這是我試圖將 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就是這樣。 它不一定是 stream 的長度。

嘗試類似的東西

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