@Override protected Binary getBinary(InputStream in) throws IOException { try { // save the file to GridFS String inputName = "tmp-" + System.nanoTime(); ObjectId id = gridFSBucket.uploadFromStream(inputName, in); // now we know length and digest GridFSFile inputFile = gridFSBucket.find(Filters.eq(METADATA_PROPERTY_FILENAME, inputName)).first(); String digest = inputFile.getMD5(); // if the digest is already known then reuse it instead GridFSFile dbFile = gridFSBucket.find(Filters.eq(METADATA_PROPERTY_FILENAME, digest)).first(); if (dbFile == null) { // no existing file, set its filename as the digest gridFSBucket.rename(id, digest); } else { // file already existed, no need for the temporary one gridFSBucket.delete(id); } return new GridFSBinary(digest, blobProviderId); } finally { in.close(); } }