IFormFile always return null in asp.net core 2.1

前端 未结 11 1838
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 11:52

Api method is looks like below

    [HttpPost]
    public async Task> MediaBrand(IFormFile file, int brandId)
         


        
相关标签:
11条回答
  • 2021-01-11 12:27

    Change your method argument to take below model and add [FromForm], it should work.

    public class FileUploadViewModel
    {
        public IFormFile File { get; set; }
        public int BrandId { get; set; }
    }
    
    public async Task<BaseListResponse<MediaStorageModel>> MediaBrand([FromForm] FileUploadViewModel viewModel)
    
    0 讨论(0)
  • 2021-01-11 12:30

    I have found a workaround to make it work:

    Use HttpPut instead of HttPost on the controller action.

    I was also surprised by this behavior. If someone can explain why it fixes the issue, it would help me.

    0 讨论(0)
  • 2021-01-11 12:32

    In your form use

    enctype="multipart/form-data"

    0 讨论(0)
  • 2021-01-11 12:33

    In my case it works as follows in net core

    Controller:

    [HttpPost]
    public IActionResult ReadFormFile([FromForm]IFormFile miCsv)
    {
    
    
    }
    

    Request body: Use as key the same name as the parameter

    Request Header: Use as Content-Type: multipart/form-data; boundary=xxxxxxxxxxx the boundary can be any value

    0 讨论(0)
  • 2021-01-11 12:37

    If you use javascript and FormData object you need set the name of each file to 'files'

    this.files.forEach((f) => {
             formData.append("files", f, `${this.path}/${f.name}`);
          }); 
    

    if you use other name in your post you need to set it in the attribute of the post method

    formData.append("someName", f, `${this.path}/${f.name}`);
    
     public async Task<IActionResult> Post([FromForm(Name ="someName")] List<IFormFile> files)
    

    Dont forget to set content-type

    'Content-Type': 'multipart/form-data'
    
    0 讨论(0)
提交回复
热议问题