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

Save Image URL to the User in SailsJS

我正在使用 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] });

您正在将图像上传到“/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] })
})
},