Search code examples
javascriptnode.jssails.jssails-mongosails-skipper

Save Image URL to the User in SailsJS


I'm creating an api using Sails JS v1.0.0

I have an action to upload an image to the server and it's working great but the problem I'm having is that I want to save the image URL to the user uploaded the image. It's the user profile image.

The code seems to work fine but I get an error in the terminal after uploading the image. I guess it has something with the callbacks.

Here is my controller:

let fs = require('fs');

module.exports = {

    upload : async function(req, res) {
      req.file('image').upload({ dirname : process.cwd() + '/assets/images/profile' }, function(err, uploadedImage) {
        if (err) return res.negotiate(err);
        let filename = uploadedImage[0].fd.substring(uploadedImage[0].fd.lastIndexOf('/')+1);
        let uploadLocation = process.cwd() +'/assets/images/uploads/' + filename;
        let tempLocation = process.cwd() + '/.tmp/public/images/uploads/' + filename;
        fs.createReadStream(uploadLocation).pipe(fs.createWriteStream(tempLocation));
        res.json({ files : uploadedImage[0].fd.split('assets/')[1] })
      })
    }

};

About the read stream to the .tmp folder, I wrote it to make the image available the moment it gets uploaded.

I tried to query for the user right before the

res.json({ files : uploadedImage[0].fd.split('assets/')[1] })

line, but it gives me an error in the terminal.

What's the best way to implement this code?

User.update({ id : req.body.id }).set({ image : uploadedImage[0].fd.split('images/')[1] });

Solution

  • You are uploading images to '/assets/images/profile' and trying to fetch it from '/assets/images/uploads/'. Also wrong path in tempLocation variable too. Change your code to following and it will hopefully start working

    upload : async function(req, res) {
      req.file('image').upload({ dirname : process.cwd() + '/assets/images/profile' },
      async function(err, uploadedImage) {
      if (err) return res.negotiate(err);
      let filename = uploadedImage[0].fd.substring(uploadedImage[0].fd.lastIndexOf('/')+1);
      let uploadLocation = process.cwd() +'/assets/images/profile/' + filename;
      let tempLocation = process.cwd() + '/.tmp/public/images/profile/' + filename;
      fs.createReadStream(uploadLocation).pipe(fs.createWriteStream(tempLocation));
    
      await User.update({ id : req.body.id }).set({ image : uploadedImage[0].fd.split('images/')[1] });
    
      res.json({ files : uploadedImage[0].fd.split('assets/')[1] })
    })
    },