ASP.Core Uploading image with Axios

Viewed 2391

I am trying to upload an image to a server with Axios, but having Error 400 "Bad Request". I have tried many different ways to implement it: explicitly specifying a "Content-Type", changing controller, trying $.ajax, etc. from Google.

A brief description of what I am expecting: I choose an image as suggested by <input/> and once I submit my choice it is sent to the server.

Currently, in my controller, I set a breakpoint, however, I've never seen request entering it.

My stack is Asp.Core WebAPI + React.js + Axios. I have stopped on the following code:

Controller:

[Route("api/char")]
[ApiController]
public class CharacterController : ControllerBase
{
    [HttpPost]
    [Route("[action]")]
    public async Task<IActionResult> SetProfilePhoto(IFormFile file)
    {
        return Ok();
    }
}

React Component:

export default class BioEdit extends React.Component {
        ...
        changePhoto = event => {
             event.preventDefault();

             const file = event.target.files[0];

             const formData = new FormData();
             formData.append("File", file);

             Axios.post("api/char/SetProfilePhoto", formData, {
                  headers: { 'Content-Type': 'multipart/form-data' }
             })
                  .catch(error => console.log(error));
         }
         render(){
             return (
                 <label >
                     <img src={this.state.char.image} width="30%" height="30%" className="border border-secondary" />
                     <input type="file" style={{ display: "none" }} accept="image/*" onChange={this.changePhoto} />
                 </label>
            );
        }
    }

Here is what I have in the browser (Yandex browser it is to be specific, based on Chrome):

browser console

2 Answers

There are two options based on whether you need API Controller or not.

  • The first is to remove the APIControllerAttribute from off your controller, then nothing else is needed to be done;
  • The second is to set up the Startup.cs as doc prescribes. Adding services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); solved my problem.

NOTE: it is not necessary to set up headers to undefined or whatever. Axios deals with it in the right way itself.

add undefined content type. it should work then

         Axios.post("api/char/SetProfilePhoto", formData, {
              headers: { 'Content-Type': undefined }
         })
Related