Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

465
Views
Send file to (fetch to c# web api)

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
{
   //.....
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!