简体   繁体   English

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

[英]Save Image URL to the User in SailsJS

I'm creating an api using Sails JS v1.0.0 我正在使用Sails JS v1.0.0创建一个api

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. 我有一个动作可以将图像上传到服务器,并且运行良好,但是我遇到的问题是我想将图像URL保存到上传图像的用户。 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. 关于读取到.tmp文件夹的流,我将其写入以使图像在上载后立即可用。

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

You are uploading images to '/assets/images/profile' and trying to fetch it from '/assets/images/uploads/'. 您正在将图像上传到“ / assets / images / profile”,并尝试从“ / assets / images / uploads /”中获取。 Also wrong path in tempLocation variable too. tempLocation变量中的路径也错误。 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] })
})
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM