0

I am using simple code below to retrieve a file stored in mongodb. The file is downloaded but not in PDF format. While writing the file, I have set the content_type in grid-fs api to application/pdf and I see the file is there in Mongo. The file downloaded is just BigBangTheory, not BigBangTheory.pdf. Other formats e.g. text/html having the same issue.

res.set('Content-Type', 'application/pdf');
gfs.createReadStream({ filename: 'BigBangTheory.pdf' }).pipe(res);

Thanks! I appreciate your help!

RatDon
  • 3,403
  • 8
  • 43
  • 85
honitus
  • 1
  • 2
  • If you rename the downloaded file as BigBangTheory.pdf, does it open correctly? If so, then I think you just need to set the Content-Disposition header in the response. For example, `res.set('Content-Disposition', 'attachment; filename=BigBangTheory.pdf);` – MForMarlon Apr 01 '15 at 03:12

1 Answers1

0

You might want to check how you're uploading the file. I had a similar issue trying to download a pdf file from gridfs-stream but the file was unreadable. I found out the that form-part data as part of the upload was attaching information to the head and foot of the document as part of the request. My solution was to use busboy to manage the form-part upload :

var Busboy = require("busboy");
exports.create = function(req, res, next) {

    var busboy = new Busboy({ headers : req.headers });

    busboy.on("file", function(fieldname, file, filename, encoding, mimetype) {

        var writeStream = gfs.createWriteStream({ filename : filename, contentType : mimetype, metadata : { account : req.user.parameters["account_id"] } });

        writeStream.on('close', function(file) {
            res.json({ _id : file._id, filename : filename, metadata : { account : req.user.parameters["account_id"], uploaded : new Date() } });
        });

        writeStream.on('error', function(err) {
            console.log(err);
        });

        file.pipe(writeStream);
    });
    req.pipe(busboy);
};
nebulr
  • 641
  • 6
  • 7