I editted the whole question because it was very long and confusing.
Clear, concise new question
I was sending all data from my forms as a stringified JSON, but now I need to append a file, so I can no longer do this. How do I send my form data from React to an ASP.NET Core API in a format that allows appending files?
Old question
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"
}
APIandReactcode for how you are uploading the image file? So that it can be resolved easily.IFormFile Imageor image asbase64where the image will be served asstringforloop I was using to append the values to the formData. I checked the object after the loop and it seemed ok but I decided to try change it toObject.keys(data).forEachand it worked. I still don't understand why but it works