[Route("api/file")]
[Produces("application/json")]
[Consumes("application/json", "application/json-patch+json", "multipart/form-data")]
[ApiController]
public class FileController : ControllerBase
{
public FileController()
{
}
[HttpPost]
public async Task<IActionResult> PostProfilePicture([FromQuery]IFormFile file)
{
var stream = file.OpenReadStream();
var name = file.FileName;
return null;
}
}
邮递员
调试
最后的文件= null 如何解决这个问题?
答案 0 :(得分:2)
您将其作为x-www-form-urlencoded
发送。您必须将其作为multipart/form-data
发送。文件只能在此模式下上载,因此IFormFile
在所有其他模式下也将是null
。
x-www-form-urlencoded
是默认模式,仅用于在请求正文中发送密钥/值编码对。
也不需要[FromQuery]
,因为您不能通过查询参数上传文件。
答案 1 :(得分:1)
您需要更改选择模型绑定程序将从其解析IFormFile
实例的源的属性。代替[FromQuery]
到[FromForm]
:
public async Task<IActionResult> PostProfilePicture([FromForm]IFormFile file)
答案 2 :(得分:1)
我猜您从IFormFile
中得到的是空值,因为您在Controller类而不是controller方法上指定了此操作的必需属性。如下更新代码即可解决问题。
[Route("api/file")]
[ApiController]
public class FileController : ControllerBase
{
public FileController()
{
}
[HttpPost]
[Produces("application/json")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> PostProfilePicture([FromForm]IFormFile file)
{
var stream = file.OpenReadStream();
var name = file.FileName;
return null;
}
}
希望这可以解决您的问题。