4

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

0

2 Answers 2

2

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.

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

Comments

0

add undefined content type. it should work then

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

1 Comment

I have tried that as well, specifying it as a constant with JSON. Suppose it should have had the same effect, but it haven’t. So, the problem is still actual.

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.