1

I tried to post an array of string from ReactJS to WebApi but I got just one string [0].

Here is my ReactJS code:

import React, { useState } from "react";
import axios from "axios";

export const FileUpload = () => {

  const [files, setFiles] = useState();
  const [fileNames, setFileNames] = useState();

  const saveFile = (e) => {

    var tempfiles = files;
    if (tempfiles == null) {
      tempfiles = [];
    }
    tempfiles.push(e.target.files[0]);
    setFiles(tempfiles);

    var tempFileNames = fileNames;
    if (tempFileNames == null) {
      tempFileNames = [];
    }
    tempFileNames.push(e.target.files[0].name)
    setFileNames(tempFileNames);
  };

  const uploadFile = async (e) => {
    debugger
    const formData = new FormData();

    //upload many
    for (let i = 0; i < files.length; i++) {
      formData.append("Files[${i}]", files[i]);
      // formData.append('FileNames[${i}]', fileNames[i]);
    }

    //upload 1
    // formData.append("FormFile", file);


    //add test data
    formData.append('TestField', 'abcxyz');
    formData.append('FileNames', fileNames);
    formData.append('ProjectId', 123);
    formData.append('NameToDisclose', false);
    //

    try {
      //upload many
      const res = await axios.post("https://localhost:44376/api/test/UploadMany", formData);

      ////upload 1
      // const res = await axios.post("https://localhost:44376/api/test/Upload", formData);

      console.log(res);
    } catch (ex) {
      console.log(ex);
    }
  };

  return (
    <>
      <input type="file" onChange={saveFile} />
      <input type="button" value="upload" onClick={uploadFile} />
    </>
  );
};

Here is my Controller:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using UploadFileToWebApiBE.Model;

namespace UploadFileToWebApiBE.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpPost]
        [Route("UploadMany")]
        public ActionResult Post([FromForm]UploadFileMany files)
        {
            try
            {
                files.Files = Request.Form.Files;

                return StatusCode(StatusCodes.Status201Created);
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }
        
    }
}

Here is my UploadFileMany:

using Microsoft.AspNetCore.Http;

namespace UploadFileToWebApiBE.Model
{
    public class UploadFileMany
    {
        public string TestField { get; set; }

        public IFormFileCollection Files { get; set; }

        public string[] FileNames { get; set; }

        public int ProjectId { get; set; }

        public bool NameToDisclose { get; set; } = false;
    }
}

This is the data from ReactJS:

enter image description here

This is the data from WebApi:

enter image description here

I want to have 3 items for FileNames, not one item seperated by a comma. Any help will be much appreciated.

1 Answer 1

1

Try to pass filenames as a JSON string by using:

formData.append('FileNames', JSON.stringify(fileNames);

and then parse the JSON string in your back-end codes. because i remember that formData in JavaScript doesn't accept arrays and objects as input. You can stringify them and pass your arrays and objects in a standard format. I hope this works for you

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

3 Comments

Still one string but it becomes Json string: ["New Microsoft Word Document.docx","text1.txt","New Microsoft Excel Worksheet.xlsx"]
@anhtv13 : So it's OK.If you look at ["New Microsoft Word Document.docx","text1.txt","New Microsoft Excel Worksheet.xlsx"] carefully you'll see it's an array with 3 strings . just parse the JSON string and you'll have an array with 3 items.
Yes I can deserialize it into array string. Your solution doesn't give me straight 3 strings but anyway it solves the problem. I give you an upvote. Thank you :)

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.