0

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

1 回答 1

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] })
})
},
于 2018-07-10T16:38:18.337 回答