Reputation: 277
I'm trying to store and retrieve images with GridFs using Spring.
Method for uploading 1:
public void savePicture(InputStream photo, Customer customer) {
Query query = new Query (Criteria.where("filename").is(customer.getId()).and("metadata.status").is("active"));
Update update = new Update().set("metadata.status" , "false");
WriteResult wr = this.mongoTemplate.updateFirst(query, update, "fs.files");
if (!wr.getLastConcern().callGetLastError()){
DBObject metaData = new BasicDBObject();
metaData.put("status", "active");
String imageFormat = this.imageUtils.getImageFormat(photo);
String contentType = "image/" + imageFormat;
GridFSFile gridFsFile = this.gridFsTemplate.store(photo, customer.getId(), contentType, metaData);
}
}
Method for uploading 2 (differs only when invoking this.gridFsTemplage.store)
public void saveProfilePicture(InputStream photo, Customer customer) {
Query query = new Query (Criteria.where("filename").is(customer.getId()).and("metadata.status").is("active"));
Update update = new Update().set("metadata.status" , "false");
WriteResult wr = this.mongoTemplate.updateFirst(query, update, "fs.files");
if (!wr.getLastConcern().callGetLastError()){
DBObject metaData = new BasicDBObject();
metaData.put("status", "active");
GridFSFile gridFsFile = this.gridFsTemplate.store(photo, customer.getId(), metaData);
}
}
Method for downloading:
public InputStream getPicture(Customer customer){
Query query = new Query(Criteria.where("filename").is(customer.getId()).and("metadata.status").is("active"));
GridFSDBFile gridFsDBFile = this.gridFsTemplate.findOne(query);
return gridFsDBFile.getInputStream();
}
Both methods for uploading work and write on MongoDB/GridFS, but when I use method 1 I cannot download the picture and it appears to be corrupted. For example if I upload a picture of 7.8KB the downloaded version is ligther of 500 bytes (7.3KB) and I cannot open it with an image viewer. When I use the method 2 for upload everything works fine.
Any idea?
Upvotes: 1
Views: 1427
Reputation: 1935
If you run this on MongoShell , you can see gridfs files: db.fs.files.find()
Now, the problem in your method 1 is that you are not specifying the full name of the file.(If
you dont specify the full name i.e filename + extension)
GridFSFile gridFsFile = this.gridFsTemplate.store(photo, customer.getId(), contentType, metaData);
Should be changed to=>
GridFSFile gridFsFile = this.gridFsTemplate.store(photo, customer.getId() + "." + imageFormat, contentType, metaData);
Upvotes: 1