我正在编写一个spring mvc webapp,它使用MultipartFile
类型的图片转换为byte[]
然后转换为Inputstream
并将其存储在 MongoDB 中使用GridFsTemplate
。
现在的问题是我想在网页中显示存储的图像,但每当我尝试时,数据库都会将图像文件返回为GridFSDBFiles
,因此抛出以下异常:
java.lang.ClassCastException:com.mongodb.gridfs.GridFSDBFile无法强制转换为org.springframework.web.multipart.MultipartFile
这是我存储图像的DAO:
public void saveScan(Scan scan) throws IOException {
String owner = String.valueOf(scan.getPatientId());
String fileName = String.valueOf(scan.getPatientId() + "" + scan.getScanType());
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
String uploadTime = simpleDateFormat.format(date);
System.out.println("the scan type is " + scan.getScanType());
DBObject metaData = new BasicDBObject();
metaData.put("owner", owner);
metaData.put("fileName", fileName);
metaData.put("uploadTime", uploadTime);
byte[] scanBytes = scan.getScan().getBytes();
InputStream inputStream = new ByteArrayInputStream(scanBytes);
scanDaoImpl.SaveScan(inputStream, fileName, "image/jpeg", metaData);
}
这是为了重新拍摄图像:
public MultipartFile findOneScan(BigInteger patientId) {
MultipartFile multipartFile = (MultipartFile) gridFsTemplate
.findOne(new Query(Criteria.where("metadata.owner").is(patientId)));
return multipartFile;
这是我获取图像的控制器
@ResponseBody
@RequestMapping(value = "/patients/{id}/scan", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> scanImage(@PathVariable("id") BigInteger id) throws IOException {
logger.debug("scanImage() is finding Image to display");
byte[] bs = patientScanServiceImpl.findOne(id).getBytes();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.IMAGE_JPEG);
httpHeaders.setCacheControl(CacheControl.noCache().getHeaderValue());
return new ResponseEntity<byte[]>(bs, httpHeaders, HttpStatus.OK);
}
这是我的百里香图像标记:
<span>
<img th:src="@{/patients/{patientid}/scan(patientid=${patient.id})}" width="250" height="250"/>
</span>
答案 0 :(得分:0)
现在我对此有了更多的了解,我终于找到了解决方案。您无法直接将 gridFSDBFile 强制转换为 byte [] ;必须先将其转换为 OutputStream ,然后再转换为 byte [] (如果必须显示)。所以我允许我的DAO方法返回 GridFSDBFile 但是在服务层我将 GridFSDBFile 转换为 ByteArrayOutputStream 然后转换为 byte [ ] 即可。 现在我用于检索图像的DAO方法是
public GridFSDBFile findOneScan(BigInteger patientId, String scanType) {
String fileName = String.valueOf(patientId + "" + scanType);
GridFSDBFile gridFSDBFile = gridFsTemplate.findOne(new Query(Criteria.where("metadata.fileName").is(fileName)));
return gridFSDBFile;
我的服务层是为控制器提供的
public byte[] findOne(BigInteger patientId, String scanType) throws IOException {
GridFSDBFile gridFSDBFile = scanRepository.findOneScan(patientId, scanType);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
gridFSDBFile.writeTo(outputStream);
byte[] bs = outputStream.toByteArray();
return bs;
}
整件事情都很好。