Issue with downloading a file from GridFS in MongoDB/NodeJs/GridFS stack

2.5k views Asked by At

I am working on a NodeJs API and I chose to use GridFS to store and download files. I have two API's for this matter: Upload and Download. Both API's work perfectly when I call them using Postman; however I have an issue downloading files using browser. It seems the browser see's the 200 HTTP code and expects the file to be there immediately while the content is still being streamed. Hence, it complains that the image or PDF or etc has an error or has invalid format. The only type of file that is working is MP3 for which the browser starts a MP3 streaming plugin which plays that music.

var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var gfs = new Grid(mongoose.connection.db);
//.... some code in here
exports.download = function(req, res) {
    gfs.files.find({ "_id": mongoose.Types.ObjectId(req.params.id) }).toArray(function (err, files) {
            if(files.length===0){
            return res.status(400).send({
                message: 'File not found'
            });
            }



        var readstream = gfs.createReadStream({
              filename: files[0].filename
        });

        readstream.pipe(res);
    });
};

I used Fiddler to catch request and response:

This is the request:

GET http://localhost:9000/api/file/download/5586fd1a04de649c4eff2223?access_token=bluhbluhbluhbluhbluh HTTP/1.1
Host: localhost:9000
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,fa;q=0.6
Cookie: _ga=xxxxxxxxxxxxx; wp-settings-1=editor%3Dhtml%26align%3Dleft%26unfold%3D1%26mfold%3Do%26hidetb%3D1; wp-settings-time-1=1434314682; session_id=xxxxxxxxxxxxxxxxx; connect.sid=xxxxxxxxxx; token=xxxxxxxxxx

and this is the response:

HTTP/1.1 200 OK
X-Powered-By: Express
content-length: 2412930
Date: Mon, 22 Jun 2015 16:45:04 GMT
Connection: keep-alive

%PDF-1.4
%    
< The rest of  PDF content comes in here >

Any ideas how can I fix this?

1

There are 1 answers

4
Rahat Mahbub On

Sounds like the issue is with MIME type. Add the node-mime module and try the following:

//Get Readstream code here
var mimetype = mime.lookup(files[0].filename);

res.setHeader('Content-disposition', 'attachment; filename=' + files[0].filename);
res.setHeader('Content-type', mimetype);

readstream.pipe(res);

You could also set mimetype to application/pdf to test it out with your PDF File, first.