简体   繁体   English

从 ExpressJs 发送文件到 React

[英]Sending files to React from ExpressJs

I know we can use multer to handling with multipart form datas and ı'm storing them in server and mongoDb.我知道我们可以使用 multer 来处理多部分表单数据,并将它们存储在服务器和 mongoDb 中。 Here ı'm registering a user and I'm saving the image as string to mongoDb ,but the real image is on /public/img/ So,这里我正在注册一个用户,我将图像作为字符串保存到 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));
};

Now I wanna send the user which is requested;现在我想发送请求的用户; How do ı access the image from /public/img bcz user.image is String.我如何从 /public/img 访问图像 bcz user.image 是字符串。 Should ı send the image seperately?我应该单独发送图像吗?

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

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

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

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