I have an ASP.NET Core MVC app attempting to upload an IFormFile. However, the IFormFile is always null. None of the other solutions I've found have solved this issue. What am I doing wrong?
Model
public class EmailForm { [Display(Name = "Add a picture")] [DataType(DataType.Upload)] [FileExtensions(Extensions = "jpg,png,gif,jpeg,bmp,svg")] public IFormFile SubmitterPicture { get; set; } }
Controller
public async Task<ActionResult> Contribute([Bind("SubmitterPicture")] EmailForm model) { if (ModelState.IsValid) { //Do some stuff } }
View
<form method="post" asp-action="Contribute" asp-antiforgery="true" enctype="multipart/form-data" > <div class="form-group" > <div class="col-md-2">@Html.LabelFor(m => m.SubmitterPicture)</div> <div class="col-md-4"> <input type="file" name="SubmitterPicture" id="SubmitterPicture" /> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" class="btn btn-default" value="Contribute" /> </div> </div>
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. 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.
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.
<form method="post" enctype="multipart/form-data"> </form>
enctype="multipart/form-data"
The multipart form data is the key.
You can alternatively get the file from the HttpContext.Request.Form.Files
and get rid of the IFormFile
interface in your model. I recommend this method as I believe that files have nothing to do with data models.
The example would be:
public IActionResult Index() { //Please note that if no form data is posted // HttpContext.Request.Form will throw an exception if (HttpContext.Request.Form.Files[0] != null) { var file = HttpContext.Request.Form.Files[0]; using (FileStream fs = new FileStream("Your Path", FileMode.CreateNew, FileAccess.Write, FileShare.Write)) { file.CopyTo(fs); } } return View(); }
If this method also fails, that means there is something wrong with the multipart
request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With