redstone-dart / redstone

A metadata driven microframework for Dart.
http://redstone-dart.github.io/redstone
MIT License
342 stars 42 forks source link

How to serve files stored in Mongo Dart's GridFS? #66

Closed cgarciae closed 9 years ago

cgarciae commented 9 years ago

By any chance, do you happen to know how to efficiently serve files stored in GridFS? Currently I have this code that works

@app.Route("/public/get/file/:fileID")
getFile(@app.Attr() MongoDb dbConn, String fileID)
{
    GridFS gridFS = new GridFS (dbConn.innerConn);
    ObjectId objID = StringToId(fileID);

    return gridFS.findOne(where.id(objID)).then((GridOut gridOut)
    {        
        File file = new File('temp${gridOut.filename}');   
        return gridOut.writeToFile(file).then((_) => file);
    });
}

BUT I have to create an actual File in the system and it seems very inefficient (almost killing the whole purpose of using GridFS), apart that I have to worry about deleting it later (which doesn't seem straight forward in Redstone since I need the last Future to return a File for it to work).

GridOut.writeTo (IOSink out) catches my eye but I have no idea what an IOSink is or even how to create one since its an abstract class.

Any idea on how to solve this problem?

luizmineo commented 9 years ago

Is there a way to read the data as a Stream<List<int>>? If so, you can create and return a shelf.Response object directly. Example:

return new shelf.Response.ok(data, headers: { "Content-Type": " ... " }); // You'll have to set the content-type of the file

I'm not familiar with the GridFS API, but maybe you can receive a proper answer opening a issue for mongo-dart, or asking for help in StackOverflow.

cgarciae commented 9 years ago

Thanks! Manage to create a Stream<List<int>> to serve the data with shelf! I'll expand the wiki with my test code if anyone needs it.

rahulakash commented 8 years ago

Hello @cgarciae

Thanks for your post here. I am currently in the same situation where I have to serve the file content from GridFs, is there a way to serve file contents without having to save the file in the system? I see that you have achieved it through Stream<List<int>> It will be very helpful if you could share your idea on this.

Thanks in advance.

Pacane commented 8 years ago

@rahulakash Not sure what the API looks like for GridFS, but for the streaming part, you might want to look at this

https://github.com/dart-lang/shelf/issues/54

rahulakash commented 8 years ago

@Pacane Thank you for the suggestion. I will update here with the results once I try this and get it to work.