将文件发送到(获取到C#Web API)

发布于 2025-01-23 06:15:29 字数 847 浏览 4 评论 0原文

我尝试将JS FETXH API的文件发送到ASP .NET 6 WebAPI,并获得400个状态。

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);
    }
}

如果删除FormData并发送“文件”会产生相同的错误。 如果删除“ content-type”在每种情况下都获得415状态。 如果将“ content-type”设置为“应用程序/json”和iformfile更改为字符串,则将JSON发送,则可以正常工作。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世界等同你 2025-01-30 06:15:29

1. [来自Body]使用接收application/json数据。您需要更改[来自Body][From Form]

2.使用fetchformdata。未设置content-type标题。

下面的整个工作演示:

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

API控制器:

[HttpPost]
public async Task<ActionResult> Index([FromForm] IFormFile file)
{
   //.....
}

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)
{
   //.....
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文