简体   繁体   中英

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.

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)
{
   //.....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM