ayon
ayon

Reputation: 2180

Get download url of Uploaded image in Sails.JS

I am working on an Api in Sails.js where I need to upload image to server through api and get url of that uploaded image for later use from Mobile App. For doing this, my upload codes are as follows

upload: function  (req, res) {

    var uploadPath = '../../assets/images' ;
    req.file('avatar').upload({ dirname: uploadPath },function onUploadComplete (err, files) {

        if (err) {
            return res.serverError(err);
        } else {
            var image = files[0];
            var fd = image.fd ;
            var index = fd.lastIndexOf('/');
            var imageName = fd.substring(index+1 , fd.length);
            return res.json({ image : '/images/' + imageName });
        }
    });
}

This gives me result like the following one...

{
    "image": "/images/bc4f03ec-0d9c-4553-b59a-9ddec427a265.jpg"
}

If I append the path with my localhost like this

http://localhost:1337/images/bc4f03ec-0d9c-4553-b59a-9ddec427a265.jpg

it works and image is loading in the browser. But when I deploy my application to production server, it's not working and giving me 404 error.

To solve this problem, I have already written another get action like this

download: function (req, res) {
    res.sendfile(req.path.substr(1));
},

where /routes entry is

 'get /images/*' : {
        controller : 'FileController',
        action : 'download'
    }

But that didn't help, I am getting 404 at localhost.

Can anyone suggest me how can I solve this problem ?

Upvotes: 1

Views: 2513

Answers (1)

MrVinz
MrVinz

Reputation: 874

Seems you have a grunt issue. The file served in your http://example.com/images/ are in fact in .tmp/public/images/ and a grunt task is syncing the asset folder with the tmp folder.

Try to run a grunt command in your project folder, if doesn't work try an npm install grunt sometimes the global npm installed grunt don't work.

Also make sure grunt can write to the folder .tmp;)

here are two other post which may help https://stackoverflow.com/a/20363247/4322950 https://stackoverflow.com/a/20340354/4322950

Upvotes: 1

Related Questions