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.
CodePudding user response:
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)
{
//.....
}