将文件发送到(获取到C#Web API)
我尝试将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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1.
[来自Body]
使用接收application/json
数据。您需要更改[来自Body]
到[From Form]
2.使用
fetch
和formdata
。未设置content-type
标题。下面的整个工作演示:
API控制器:
1.
[FromBody]
is used receiveapplication/json
data. You need change[FromBody]
to[FromForm]
2.To upload files using
fetch
andFormData
.you must not setContent-Type
header.Whole working demo below:
Api controller: