簡體   English   中英

為什么文件IFormFile = null?

[英]Why file IFormFile = null?

[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如何解決此問題?

您將其發送為x-www-form-urlencoded 您必須將其作為multipart/form-data 文件只能在此模式下上載,因此IFormFile在所有其他模式下也將為null

x-www-form-urlencoded是默認模式,僅用於在請求正文中發送密鑰/值編碼對。

另外, [FromQuery]也不是必需的,因為您無法通過查詢參數上傳文件。

您需要更改屬性,該屬性選擇模型綁定程序將從中解析IFormFile實例的源。 代替[FromQuery][FromForm]

public async Task<IActionResult> PostProfilePicture([FromForm]IFormFile file)

我想您從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;
    }
}

希望這能解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM