Home > Back-end >  Upload file from React form to ASP.NET Core API
Upload file from React form to ASP.NET Core API

Time:06-06

I have several forms working perfectly: I send the data using fetch from React and receive it correctly as body in my ASP.NET Core API.

However, I need to send files now, and I don't know how to append them since I am just sending all of my content in a strinfified JSON.

fetch("localhost/api/test", {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
}).then(result => result.json()).then(
    (result) => {
        console.log(result);
    }
);

I tried sending a FormData object built like this instead of the JSON.stringify(body).

let formData = new FormData();
for (var property in body) {
    formData.append(property, body[property]);
}

But when I send this object instead of the stringified JSON I always get null for all the values in ASP.NET Core.

I also tried sending this:

URLSearchParams(data)

And this:

let formBody = [];
for (var property in details) {
    var encodedKey = encodeURIComponent(property);
    var encodedValue = encodeURIComponent(details[property]);
    formBody.push(encodedKey   "="   encodedValue);
}
formBody = formBody.join("&");

And I tried different combinations of headers with every type of data encoding:

  • No headers
  • 'Content-Type': 'multipart/formdata'
  • 'Content-Type': 'application/json'
  • 'Content-Type': 'application/x-www-form-urlencoded'

I also tried getting the data from ASP.NET with both [FromBody] and [FromForm].

I think I have tried every possible combination of all the options I have explained above, with no result. I always get null values in my API.

Edit:

Right now, I am not even trying to send a file. I am trying to successfully send common data in the proper format before trying to attach a file. I don't know if I should change the title of the question.

This is my API code:

[HttpPost]
[Route("login")]
public object Login([FromBody] Credentials cred)
{
    // check credentials
    return CustomResult.Ok;
}

The class Credentials:

public class Credentials
{
    public string Username { get; set; }
    public string Password { get; set; }
}

The object body from React looks like this:

{
    username: "user",
    password: "pass"
}

CodePudding user response:

No need for JSON.stringify you can remove it and content type shouldn't be.

fetch('/api/test', {
        method: "POST",
        body: body
    })

CodePudding user response:

Sorry I'm in such a rush - just worked this out myself and have to meet a friend to go fishing.... I am sending a file with some parameters. On the api side it looks like:

    public class FileUpload_Single
    {
        public IFormFile DataFile { get; set; }
        public string Params { get; set; }
    }

    // POST: api/Company (Create New)
    [HttpPost]
    [Authorize(PermissionItem.SimulationData, PermissionAction.Post)]
    [RequestSizeLimit(1024L * 1024L * 1024L)]  // 1 Gb
    [RequestFormLimits(MultipartBodyLengthLimit = 1024L * 1024L * 1024L)] // 1 Gb
    [Consumes("multipart/form-data")]
    public async virtual Task<IActionResult> Post([FromForm] FileUpload_Single data)

.... Then on the client side it looks like:

  let formData = new FormData();
  formData.append("DataFile", file);
  formData.append("Params", JSON.stringify(params));
  fetch(apicall, {
    method: "POST",
    mode: "cors",
    headers: {
      Authorization:
        "Bearer "   (localStorage.getItem("token") || "").replace(/['"] /g, ""),
      Accept: "multipart/form-data",
    },
    body: formData,
  })

With the file coming from

  const changeHandler = (event) => {
    setSelectedFile(event.target.files[0]);
    setIsSelected(true);
  };

(from my React component)

  • Related