'415 unsupported media type error while trying to upload file from react to web api

I am new to react and web api and I am getting this unsupported media type error while trying to upload my file into my web api function

enter image description here

Here is my react js code:

onFileUpload = () => {
    // Create an object of formData
    const formData = new FormData();

    console.log("FormData");

    // Update the formData object
    formData.append('myFile', this.state.selectedFile, this.state.selectedFile.name);
    console.log(this.state.selectedFile);

    // Request made to the backend api
    // Send formData object
    //axios.post("api/uploadfile", formData);

    axiosAPI.post('api/observation/Uploadfile', formData).then(response => {});
  };

The corresponding web api code is this:

[HttpPost]
        [Route("Uploadfile")]
        public IHttpActionResult Uploadfile(object formData)
        {

            try
            {

                
                return Ok(formData);
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.NoContent, "Something went wrong");
            }



        }

I am trying to upload the file and get it to my backend however I am getting this error. What does this error mean and how do I resolve this?



Solution 1:[1]

Whenever you are uploading a file, make sure to add appropriate headers to the request.

axiosAPI.post('api/observation/Uploadfile', formData, {
    headers: {
      'Content-Type': 'multipart/form-data' // <- HERE
    }
}).then(response => {});

Solution 2:[2]

Sometime the issue is on formData, you need to append file obj on formData then send to api.

const formData = new FormData(); 
var file = fileList[0].originFileObj;
formData.append("excelFormFile", file); //Append file obj to formData

//excelFormFile name similar to .NET Core Api Like c# Code : ' public async Task PostProductImport(IFormFile excelFormFile) '

Solution 3:[3]

I had the same issue, I'm using .NET 6 for the API and React with Axios for the frontend.

To be able to get the file in the controller, I had to use the "FromForm" attribute, otherwise, I was getting the 415 error when I tried to do the Post Request.

    [HttpPost]
    public async Task<IActionResult> Create([FromForm] ExampleDto dto)
    {
          /// ...
    }

To send the data from the React Application using Axios, I just created the FormData object just like you did, and made a post request without any special headers o configuration.

Hope this can help you solve your issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eduard
Solution 2 Salis Khizar Khan
Solution 3 cesarmart