【问题标题】:Sending files to React from ExpressJs从 ExpressJs 发送文件到 React
【发布时间】:2021-09-14 16:14:57
【问题描述】:

我知道我们可以使用 multer 来处理多部分表单数据,并将它们存储在服务器和 mongoDb 中。 在这里我正在注册一个用户,我将图像作为字符串保存到 mongoDb ,但真正的图像在 /public/img/ 所以,

  const body = req.body;
  const name = body.name;
  const surname = body.surname;
  const email = body.email;
  const password = body.password;
  const image = req.file.filename;
  User.findOne({ email })
    .then((isSuccess) => {
      if (isSuccess) {
        res.json("User exists!");
      }
    })
    .catch((err) => console.log(err));
  const user = new User({
    name,
    surname,
    email,
    password,
    image,
  });
  user
    .save()
    .catch((err) => {
      console.log(err);
      res.json("Something went wrong!");
    })
    .catch((err) => console.log(err));
};

现在我想发送请求的用户; 如何从 /public/img 访问图像 bcz user.image 是字符串。 我应该单独发送图像吗?

exports.getUserById = async (req, res) => {
  User.findById(req._id).then((user) => {
    if (user) {
      
    }
  });
};

【问题讨论】:

    标签: javascript node.js reactjs api express


    【解决方案1】:

    从带有文件名的存储位置读取图像文件并将其作为 data:image/png;base64 字符串作为同一响应的一部分发送,以便可以直接在 img src 属性中使用,

    【讨论】:

    • 我的意思是它有效吗?您有什么资源可以推荐给我吗?顺便说一句,谢谢。
    猜你喜欢
    • 2012-10-31
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2020-11-20
    • 1970-01-01
    • 2016-11-22
    • 2016-09-02
    相关资源
    最近更新 更多