GridFSFile file = gdfTemplate.findOne(new Query(Criteria.where("_id").is(attachmentId)));
if(file != null) {
try {
InputStream inputStream = null;
try {
inputStream = gdfTemplate.getResource(file).getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
InputStreamResource inputStreamResource = null;
try {
inputStreamResource = new InputStreamResource(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
HttpHeaders header = new HttpHeaders();
header.setContentLength(file.getLength());
String contentType = file.getMetadata().get("contentType").toString();
header.setContentType(MediaType.parseMediaType(contentType));
return new ResponseEntity<>(inputStreamResource, header, HttpStatus.OK);
}catch (Exception ex){
ex.printStackTrace();
}
}else{
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Mongodb Spring 下载文件
于 2024-03-06 10:05:08 首次发布
文章描述了使用MongoDBGridFS在查询到文件后,如何读取文件内容,设置HTTP头并返回给客户端,以及处理文件未找到的情况。
摘要由CSDN通过智能技术生成