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