Retrieving Files from MongoDB GridFS Using GridFsResource in Spring

MongoDB’s GridFS is designed to store and retrieve files that exceed the BSON document size limit of 16MB by splitting them into smaller chunks. In Spring applications using Spring Data MongoDB, GridFsResource provides a conveneint abstraction for reading these files.

GridFS uses two collections: fs.files stores metadata about each file, while fs.chunks holds the actual binary data in segments—typically 255KB each.

To read a file stored in GridFS, first locate its metadata using GridFsTemplate, then wrap it in a GridFsResource to access its content as an InputStream. Here's how to implement this:

@Autowired
private GridFsTemplate gridFsTemplate;

public byte[] fetchFileContent(ObjectId fileId) throws IOException {
    Query query = Query.query(Criteria.where("_id").is(fileId));
    GridFSFile gridFile = gridFsTemplate.findOne(query);
    
    if (gridFile == null) {
        throw new FileNotFoundException("File not found with ID: " + fileId);
    }
    
    try (InputStream stream = gridFsTemplate.getResource(gridFile).getInputStream()) {
        return stream.readAllBytes();
    }
}

This method queries the fs.files collection by _id, retrieves the corresponding GridFSFile, and then uses GridFsTemplate.getResource() to obtain a GridFsResource. The input stream from this resource is read into a byte array.

For completeness, here’s how a file might be stored initially:

public ObjectId saveFile(InputStream source, String filename, String mimeType) {
    DBObject metadata = new BasicDBObject();
    metadata.put("contentType", mimeType);
    return gridFsTemplate.store(source, filename, mimeType, metadata);
}

Combining both operations enables full round-trip file handling:

// Store
ObjectId id = saveFile(new FileInputStream("document.pdf"), "document.pdf", "application/pdf");

// Retrieve
byte[] content = fetchFileContent(id);

This pattern integrates cleanly into REST controllers or service layers, allowing efficient management of large binary objects within MongoDB-backed Spring applicatiosn.

Tags: mongodb GridFS Spring Data java File Storage

Posted on Fri, 08 May 2026 08:15:42 +0000 by wanttoshop