Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download image from skipper-gridfs in Sails.js

I upload images to server with gridfs in my sails.js Application. My uploading codes are as follows

upload: function  (req, res) {
        req.file('avatar')
            .upload({
                adapter: require('skipper-gridfs'),
                uri: 'mongodb://localhost:27017/dbname.images'
            }, function whenDone(err, uploadedFiles) {
                if (err) return res.negotiate(err);
                else return res.ok({
                    files: uploadedFiles,
                    textParams: req.params.all()
                });
            });
    }

I get the following response from this...

{
    "files": [
        {
            "fd": "2d8910a0-8ca2-4df1-9930-6ddd721a0416.jpg",
            "size": 172883,
            "type": "image/jpeg",
            "filename": "Photo on 12-20-14 at 9.53 PM.jpg",
            "status": "bufferingOrWriting",
            "field": "avatar",
            "extra": {
                "fileId": "54aee6ced4a0e88f0dc9025f",
                "fd": "2d8910a0-8ca2-4df1-9930-6ddd721a0416.jpg",
                "dirname": "."
            }
        }
    ],
    "textParams": {}
}

My question is , if I need to download the uploaded file above , what shall I do ? I got the following code in the internet for downloading task but this does not make much sense to me. Basically I want the download url of the uploaded image that I can use that url in Mobile App to show image.

var blobAdapter = require('skipper-gridfs')({
            uri: 'mongodb://localhost:27017/dbname.images'
        });
        blobAdapter.read(filename, callback);

Can anybody help me on this ? Thanks in advance.

like image 602
ayon Avatar asked Dec 25 '22 00:12

ayon


1 Answers

After some research, I finally managed to solve the problem. I get the field fd in the response after file upload and save that to use afterwards. I went to the skipper-gridfs codes and found a 'read' method that accept that value and returns the required file. So, I just pulled that file from mongo by that method and send as a response. It's working file.

download: function (req, res) {
        var blobAdapter = require('skipper-gridfs')({
            uri: 'mongodb://localhost:27017/mydbname.images'
        });

        var fd = req.param('fd'); // value of fd comes here from get request
        blobAdapter.read(fd, function(error , file) {
            if(error) {
                res.json(error);
            } else {
                res.contentType('image/png');
                res.send(new Buffer(file));
            }
        });
    }

I hope it will help somebody like me in the future :)

like image 135
ayon Avatar answered Jan 10 '23 03:01

ayon