在SailsJS中将图片URL保存到用户

时间:2018-06-20 02:26:21

标签: javascript node.js sails.js sails-mongo sails-skipper

我正在使用Sails JS v1.0.0创建一个api

我有一个动作可以将图像上传到服务器,并且效果很好,但是我遇到的问题是我想将图像URL保存到上传图像的用户。这是用户个人资料图片。

代码似乎可以正常工作,但是上传图像后在终端中出现错误。我想它与回调有关。

这是我的控制人:

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] })
      })
    }

};

关于读取到.tmp文件夹的流,我将其写入以使图像在上载后立即可用。

我试图在

之前查询用户
res.json({ files : uploadedImage[0].fd.split('assets/')[1] })

行,但是在终端上却给我一个错误。

实现此代码的最佳方法是什么?

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

1 个答案:

答案 0 :(得分:1)

您正在将图像上传到“ / assets / images / profile”,并尝试从“ / assets / images / uploads /”中获取。 tempLocation变量中的路径也错误。将您的代码更改为关注代码,它将有望开始工作

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] })
})
},