1

I am new to Reactjs and learning it, I am trying to upload multiple images from Reactjs component and used the C# Web API in the backend, but each time I am getting the Request.Form.Files count =0 in the WEB API action method, I am able to upload the sing;e image but now trying with multiple and facing the issue, Below is the component code:

import Header from './Header'
import { Button } from 'react-bootstrap'
import { useEffect, useState } from 'react';


function Add() {

    const [productName, setProductName] = useState("");
    const [productCode, setProductCode] = useState("");
    const [productPrice, setProductPrice] = useState("");
    const [productDescription, setProductDescription] = useState("");
    const [productImage, setProductImage] = useState([]);

    // useEffect(()=>{

    //     AddProduct();

        
    // },[] )

    async function AddProduct() {

       // let data={productName, productCode, productPrice, productDescription}

        const formData = new FormData();
        for(let i=0;i<productImage.length;i++){
            // console.log(productImage)
            formData.append("productImage"+i, productImage);
       }
        // formData.append("productImage", productImage);
        formData.append("productName", productName);
        formData.append("productCode", productCode);
        formData.append("productPrice", productPrice);
        formData.append("productDescription", productDescription);
        formData.append("userName",localStorage.getItem("UserName"));

        console.warn("Sonu ", formData)
        console.log(productImage)

        let result = await fetch("https://localhost:44353/ApiProduct/AddProduct", {
            method: "POST",
            headers: {},
            body: formData,
        })
        let response=await result.json();
        if(response.status)
        {
            alert (response.successMessage)
        }
        else{
            alert (response.errorMessage)

        }

    }
    function onImageChange(e) {
        setProductImage([...e.target.files]);
      }
        return (

            <div>
                <Header />
                <h1>Add Product</h1>
                <div className='col-6 offset-3' >
                    <input type="text" placeholder='productName'  className='form-control' onChange={(e) => setProductName(e.target.value)} /><br /><br />
                    <input type="text" placeholder='productCode'  className='form-control' onChange={(e) => setProductCode(e.target.value)} /><br /><br />
                    <input type="text" placeholder='productPrice'  className='form-control' onChange={(e) => setProductPrice(e.target.value)} /><br /><br />
                    <input type="text" placeholder='productDescription'  className='form-control' onChange={(e) => setProductDescription(e.target.value)} /><br /><br />
                    <input type="file"  multiple accept=".jpg"  className='form-control' onChange={(e) => onImageChange(e)} /><br /><br />
                    

                    <Button onClick={AddProduct}>Add Products</Button>
                </div>
            </div>


        );
    }

    export default Add;
   

Below is the API Code..

 public ResponseData AddProduct([FromForm] IList<IFormFile> files)
                        {
            ProductModel productModel = new ProductModel();
            if(files?.Any())
            {
            // Each time in my case files count is showing zero.
            }
            else
            {
            // other Logic
            }
            }

1 Answer 1

1

I have used the C# Web API in the backend, but each time I am getting the Request.Form.Files count =0 in the WEB API action method, I am able to upload the sing;e image but now trying with multiple and facing the issue.

Well, to begin with your issue, while you wowuld send request to API controller you ought to match parameter name same as your controller with your fromData submit parameter. In your case, your controller parameter name is files however, you are binding your formData paramter as formData.append("productImage"+i, productImage); which is incorreect that's causing data-loss at submission.

In addition, not sure what did you mean by public ResponseData AddProduct API controller name. Furthermore, here is the complete sample how you could send list of image from your react request to Asp.net core API controller.

From Data Binding in React:

async function AddProduct(productImage) {

            const formData = new FormData();
            if (productImage.length > 0) {
             
                for (let i = 0; i < productImage.length; i++) {
                     let image = productImage[i];
                    formData.append('files', image);
                }
               
            }

            let result = await fetch("https://localhost:44353/ApiProduct/AddProduct", {
                method: "POST",
                headers: {},
                body: form,
            });
            console.log(result.status);

        }

Note: Be confirmed about AddProduct(productImage) here, productImage is each image I am passing while choosing image, you need to pass the parameter here. In addition, here form.append('files', files); files is your controller parametere must match accordingly.

Controller:

        [HttpPost]
        public async Task<IActionResult> AddProduct([FromForm] List<IFormFile> files)
        {
            return Ok(files);
        }

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.