首页 > 解决方案 > React axios 发送多张图片formdata

问题描述

我有一个反应组件,用于将多个图像上传到服务器

反应组件看起来像这样

import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { addNewProduct } from "../../redux/actions";

class Admin extends Component {

    state = {
        ProductImg: [],
    };

    handleImageChange = e => {
        const ProductImg = e.target.files
        this.setState({
            ProductImg
        })
    }

    handleProductSubmit = (event) => {
        event.preventDefault();
        this.props.addNewProduct(
            this.state.ProductImg
        );
    }

    render() {
        return (
            <div>
                <form onSubmit={this.handleProductSubmit} autoComplete="off">
                    <input type="file" id="customFile" name="ProductImg" multiple onChange={this.handleImageChange} />
                    <button type="submit" className="btn btn-dark">Upload Product</button>
                </form>
            </div>
        );
    }
}


const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({ addNewProduct }, dispatch);
};

export default connect(null, mapDispatchToProps)(Admin);

我正在将此数据发送给一个看起来像这样的动作创建者

export const addNewProduct = (ProductName, ProductCategory, ProductImg) => (dispatch) => {
    console.log("this is from inside the actions");


    console.log('============this is product images inside actions========================');
    console.log(ProductImg);
    console.log('====================================');

    const productData = new FormData();
    productData.append("ProductName", ProductName)
    productData.append("ProductCategory", ProductCategory)
    ProductImg.forEach(image => {
        productData.append("ProductImg", image);
    });

    axios.post("http://localhost:4500/products/", productData,
        {
            headers: {
                "Content-Type": "multipart/form-data"
            }
        })
        .then(res => {
            console.log('====================================');
            console.log("Success!");
            console.log('====================================');
        })
        .catch(err =>
            console.log(`The error we're getting from the backend--->${err}`))
};

我已经为它制作了接受多个图像的后端(我使用邮递员检查过)。后端以接受对象数组的方式编写

当我尝试使用它时,我收到一个错误“ProductImg.forEach 不是函数”。

我从stackoverflow查看了这个答案-> React axios multiple files upload

我该如何进行这项工作?

标签: javascriptarraysreactjsaxiosmultipartform-data

解决方案


当您上传图像时,e.target.files将为您提供未在其原型上定义函数的FileList对象实例。forEach

这里的解决方案是使用将FileList对象转换为数组Array.from

您可以将动作创建者中的代码更改为

Array.from(ProductImg).forEach(image => {
    productData.append("ProductImg", image);
});

或者您可以使用 Spread 语法,例如

[...ProductImg].forEach(image => {
    productData.append("ProductImg", image);
});

推荐阅读