Nabeel
Nabeel

Reputation: 17

How to download files stored in monogdb with gridfs using spring mvs

I have saved a file into mongoDB using gridFS like so.

    Mongo mongo = new Mongo("XXXXX", XXXX);
    DB db = mongo.getDB("XXX");
    GridFS fs = new GridFS(XXX);

    File install = new File("C:\\Users\\Nabeel\\Desktop\\docs.txt");
    GridFSInputFile inFile = fs.createFile(install);
    inFile.save();

Now I want download that file using spring MVC. I don't seep to able to find example on how i can get the file back as gridFS has converted the file into binary.

An example code would be nice as i am new to all this.

Thanks you in advance

Upvotes: 0

Views: 2228

Answers (1)

burakozgul
burakozgul

Reputation: 797

You can do something like this for serving file :

public void downloadFile(String videoId , HttpServletResponse response ) {
    InputStream is = null;  

    ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoDBConfiguration.class);
    GridFsOperations gridOperations = (GridFsOperations) ctx.getBean("YourBeanName");

    List<GridFSDBFile> result = gridOperations.find(new Query().addCriteria(Criteria.where("_id").is(videoId)));

    for (GridFSDBFile file : result) {
        try {
            /* send file */
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }

}

Send file example here: How do I return a video with Spring MVC so that it can be navigated using the html5 <video> tag?

This link about video serving but it can give you an idea. Use method 2 in the link and GridFSDBFile's getInputStream() method.

Upvotes: 1

Related Questions