1

I tried to send file by JS Fetxh API to ASP .NET 6 WebAPI and get 400 status.

let data = new FormData()
data.append('file', file)
const response = await fetch('https://localhost:7054/Pictures',
{
    method: 'POST',
    headers: {
         'Content-Type': 'multipart/form-data'
    },
    body: data
});
[HttpPost]
public async Task<ActionResult> Index([FromBody]IFormFile file)
{
    try
    {
        using (var fs = new FileStream(dir, FileMode.Create))
        {
             await file.CopyToAsync(fs);
        }
        return StatusCode(StatusCodes.Status201Created);
    }
    catch
    {
        return StatusCode(StatusCodes.Status500InternalServerError);
    }
}

If delete FormData and send 'file' get the same error. If delete 'Content-Type' get 415 status in every case. If set 'Content-Type' to 'application/json' and IFormFile change to string, then send json it works ok.

3
  • Welcome to Stack Overflow! In what way is your code not working as expected? Please elaborate on the specific problem you are observing and what debugging you have done. To learn more about this community and how we can help you, please start with the tour and read How to Ask and its linked resources. Commented Apr 20, 2022 at 17:16
  • For example, if the problem is that your catch block is being triggered and you're getting back an HTTP 500 response, then take note of the fact that your catch block ignores the actual exception. In such a case your first step would be to examine the exception being caught. Commented Apr 20, 2022 at 17:18
  • A multi-part form is MIME format and would look like following example. The multi part is the body of the message and each part starts with a new line followed by two dashes. You may be missing the dashes : learn.microsoft.com/en-us/previous-versions/office/developer/… Commented Apr 20, 2022 at 17:24

1 Answer 1

2

1.[FromBody] is used receive application/json data. You need change [FromBody] to [FromForm]

2.To upload files using fetch and FormData.you must not set Content-Type header.

Whole working demo below:

let data = new FormData();
data.append('file', file);
const response = fetch('https://localhost:7054/Pictures',
{
    method: 'POST',  
    body: data
});

Api controller:

[HttpPost]
public async Task<ActionResult> Index([FromForm] IFormFile file)
{
   //.....
}
Sign up to request clarification or add additional context in comments.

1 Comment

The working demo link is missing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.