【问题标题】:React axios send multiple images formdataReact axios 发送多张图片formdata
【发布时间】:2020-08-18 22:35:46
【问题描述】:

我有一个 react 组件,用于将多张图片上传到服务器

react 组件长这样

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

我该如何进行这项工作?

【问题讨论】:

  • 你可以添加ProductImg的日志截图吗?

标签: javascript arrays reactjs axios multipartform-data


【解决方案1】:

当您上传图片时,e.target.files 将为您提供 FileList 对象的实例,该对象的原型上没有定义 forEach 函数。

这里的解决方案是使用Array.fromFileList对象转换成数组

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

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

或者你可以使用类似的Spread语法

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

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2020-05-01
    • 2019-10-24
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 2019-01-19
    • 1970-01-01
    相关资源
    最近更新 更多