为什么 formData 不适用于多个文件?

Why formData does not work with multiple files?

我正在处理的 React 项目遇到问题:我正在尝试将多张图片上传到 Node Express API。我使用的是 formData 对象,我使用 append() 方法从组件状态附加表单字段。

在我使用 multer 的 Express 代码中,req.body 中的所有属性都在那里,但 req.files 是空的。

我也使用 formData() 更改了代码以上传单个图像并且它有效;问题似乎仅在我尝试使用 formData 对象处理多个文件时出现。我还使用常规形式(不是反应)进行了测试,这也有效!

我想知道当我将 formData 与包含多个文件的文件输入一起使用时是否遗漏了什么?

import React, { Component } from "react";
import axios from "axios";

class Form extends Component {
  constructor() {
    super();
    this.state = { images: {} };
  }

  onChangeImages = e => {
    this.setState({ images: e.target.files })
  };

  onSubmit = e => {
    e.preventDefault();

    const { images } = this.state;

    const formData = new FormData();

    formData.append("images", images);

    axios
      .post("/api/post/create", formData)
      .then(res => console.log(res.data))
      .catch(err => console.error(err));
  };

  render() {
    return (
      <form onSubmit={this.onSubmit}>

        <input
          onChange={this.onChangeImages}
          type="file"
          name="images"
          multiple
          accept="image/png, image/jpeg, image/jpg"
        />

        <br />
        <input type="submit" value="Send" />
      </form>
    );
  }
}

export default Form;

快递代码

const express = require('express');
const router = express.Router();
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });


router.post('/create', upload.array('images', 2), (req, res) => {
    console.log(req.files);
    console.log(req.body);
    res.status(200).json(req.body);
});


module.exports = router;
formData.append("images", images);

您需要依次附加每个文件。 FormData 不支持 FileList 对象。

for (let i = 0 ; i < images.length ; i++) {
    formData.append("images", images[i]);
}