Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IFormFile always return null in asp.net core 2.1

Here's how I upload file my Api action :

[HttpPost]
public async Task<BaseListResponse<MediaStorageModel>> MediaBrand(IFormFile file, int brandId) 
{
    var files = new List<IFormFile>();
    files.Add(file);

    var response = await this.Upload(files, "brand", brandId);

    return response;
}

My Postman Configuration :

postman_config

I Upgraded my api from .NET Core 2.0 to 2.1 and my code is not working

Can anyone help about this ?

like image 293
Herman Avatar asked Oct 16 '18 14:10

Herman


People also ask

Can IFormFile be null?

Note: The name of the IFormFile parameter and the name of HTML FileUpload element must be exact same, otherwise the IFormFile parameter will be NULL.

What is IFormFile C#?

What is IFormFile. ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives us access to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile also provides some methods used to store files.

How do I save a file in IFormFile?

Save a Stream to a File using C# In the above code, CopyTo method Copies the contents of the uploaded file to the target stream. If using Asynchronous API then please use CopyToAsync method which helps in Asynchronously copying the contents of the uploaded file to the target stream without blocking the main thread.


3 Answers

I've faced the same issue, I was able to fix it by applying the 'Name' named parameter to FromForm attribute with name of the File field in the form. It specifies which field in the form to bind to the method parameter. Change your method signature as shown here.

[HttpPost("status")]
public async Task<BaseListResponse<MediaStorageModel>> MediaBrand([FromForm(Name ="file")] IFormFile file, int brandId)
like image 67
Ram Kumaran Avatar answered Sep 19 '22 11:09

Ram Kumaran


Make sure the form is the correct enctype

<form asp-action="Edit" enctype="multipart/form-data">

I also had to change how the Model bind works from the generated code:

public async Task<IActionResult> Edit([Bind("Text,Example")] Example example)

to this code:

public async Task<IActionResult> Edit(Example example)
like image 25
KnuturO Avatar answered Sep 20 '22 11:09

KnuturO


In your form use

<form enctype="multipart/form-data">
like image 33
Deer Avatar answered Sep 21 '22 11:09

Deer