【问题标题】:How to pass both image file and object with values from React and retrieve it on the Node.js (express) server?如何使用 React 中的值传递图像文件和对象并在 Node.js (express) 服务器上检索它?
【发布时间】:2020-07-16 15:16:22
【问题描述】:

我的目标是从我的 React 应用程序向我的 Express 服务器发送一个请求,其中包含图像文件和带有一些值的对象。在服务器上,我想将图像保存到文件磁盘并使用其余的数据,就像我对 req.body 所做的那样

所以我将图像和数据附加到 FormData 对象中并向服务器发送请求。 我使用 Multer 将图像保存到文件磁盘并且效果很好,但问题是我无法检索其余数据:(因此)

[Object: null prototype] { document: '{"name":"Thomas","address":"page.com"}' }

客户端代码:

const formData = new FormData();
formData.append('document', JSON.stringify({ name: "Thomas", address: "page.com" }));
formData.append('image', image);

axios.post('/api/add-user-with-avatar', formData)

服务器端代码:

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public');
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  }
});

const upload = multer({ storage: storage }).fields([
  { name: 'image' },
  { name: 'document' }
]);

router.post('/add-user-with-avatar', (req, res) => {
  upload(req, res, function (err) {
    if (err) return res.status(500).json(err);

    console.log('BODY: ', req.body);
    console.log('FILE: ', req.files);
  });
});

我的问题:

  1. 从 React 发送带有图像和其他数据的请求的正确方法是什么?是否应该使用 FormData 完成?怎么做?
  2. 如何在 Express 中获取我的其余数据(例如带有文本值的对象)?

【问题讨论】:

    标签: node.js reactjs express multipartform-data multer


    【解决方案1】:

    回答 1

    您需要将图像转换为 Base64 并将其与其他对象一起传递到您的服务器。对于base 64,你可以react-file-base64

    答案 2

    要从 React 应用程序获取请求数据到 Node js,您可以简单地获取 req.body。示例代码如下:

    createPost = (req, res) => {
        const post = new Post(req.body);
        //here in post variable, you have all the json data along with your Base64 image
    };
    

    【讨论】:

    • 从我读到的每个人都使用 FormData 并且转换为 Base64 的图像大 33%。你确定这是最好的方法吗?
    • Base64 不会增加图像大小。它只是一个 Base64 格式的大字符串。
    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2015-06-13
    • 2020-06-03
    • 2012-05-21
    • 1970-01-01
    • 2016-09-27
    相关资源
    最近更新 更多