参考MongoDB官方文档GridFS的部分下载文件。
ObjectId fileId = new ObjectId("60345d38ebfcf47030e81cc9");
try (GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId)) {
int fileLength = (int) downloadStream.getGridFSFile().getLength();
byte[] bytesToWriteTo = new byte[fileLength];
downloadStream.read(bytesToWriteTo);
System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));
}
下载图片时发现图片不完整,只下载了第一个chunck。
参考stackoverflow,GridFSDownloadStreamImpl的read方法是逐chunck读取的,因此文件大小大于chunk的时候需要循环读取。修改代码,图片可以完整下载。
public void downloadMongoFile() throws Exception {
ObjectId fileId = new ObjectId("60345d38ebfcf47030e81cc9");
GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
int fileLength = (int) downloadStream.getGridFSFile().getLength();
byte[] bytes = new byte[fileLength];
OutputStream outputStream = Files.newOutputStream(Paths.get("./img.jpg"));
int bytesRead = 0;
while(bytesRead < fileLength) {
int newBytesRead = downloadStream.read(bytes);
if(newBytesRead == -1) {
throw new Exception();
}
// System.out.println("off: " + bytesRead);
outputStream.write(bytes, 0, newBytesRead);
bytesRead += newBytesRead;
}
outputStream.flush();
outputStream.close();
}