Sarthak Batra
Sarthak Batra

Reputation: 597

React axios send multiple images formdata

I have a react component that is used to upload multiple images to the server

The react component looks like this

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);

I am sending this data to an action creator which looks like this

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}`))
};

I have made the backend for it which accepts multiple images (I checked that using postman). The backend is written in a manner that it accepts an array of objects

When I try using this, I get an error "ProductImg.forEach is not a function".

I have looked at this answer from stackoverflow --> React axios multiple files upload

How do I make this work?

Upvotes: 4

Views: 4688

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281676

When you upload an image, e.target.files will give you can instance of FileList object which doesn't have a forEach function defined on its prototype.

The solution here is to convert the FileList object into an array using Array.from

You can change the code in action creator to

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

or you could use a Spread syntax like

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

Upvotes: 11

Related Questions