我试图通过ASP.NET Core上传一个文件。我的行动是:
[HttpPost]
[Route("{id}")]
public async Task<IActionResult> PostImage([FromBody] IFormFile file, [FromRoute] int id)
{
if(file.Length > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(fileName);
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", "Image-" + id + "." + fileExtension);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok(fileName + fileExtension);
}
return NotFound("File not found!");
}当我使用Postman检查它的功能时,我会遇到错误415,并且Visual Studio不会跳转到断点:
"00-d411f8c099a9ca4db6fe04ae25c47411-dadd8cca7cc36e45-00“{”类型“:"https://tools.ietf.org/html/rfc7231#section-6.5.13",”标题:“不支持媒体类型”,“状态”:415,"traceId":https://tools.ietf.org/html/rfc7231#section-6.5.13"}
如何在代码中解决这个问题?
发布于 2022-04-22 10:49:48
如果要接收IFormFile,则需要post content-type=multiple/form-data,它来自form data,而不是body。还记得将[FromBody]更改为[FromForm]。
邮差:

主计长:
[HttpPost]
[Route("{id}")]
public async Task<IActionResult> PostImage([FromForm] IFormFile file, [FromRoute] int id)
{}如果您从body中发布文件,那么您可能会发布一个字节数组。如果您需要将IFormFile file更改为byte[] file。
https://stackoverflow.com/questions/71966380
复制相似问题