[英]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.