【问题标题】:Why formData does not work with multiple files?为什么 formData 不适用于多个文件?
【发布时间】:2019-06-13 15:27:03
【问题描述】:

我正在处理的 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;

【问题讨论】:

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


    【解决方案1】:
    formData.append("images", images);
    

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

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

    【讨论】:

    • 谢谢!节省了很多时间。 (y)
    • 这个应该到处提到!
    • 确实应该处处提及。
    • 用“images”键创建另一个字段。我很困惑。
    • 它工作得很好,谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2011-11-15
    相关资源
    最近更新 更多