Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC. HttpPostedFileBase is always null

I need some help. I'm trying to upload files using <input type="file">. Here is my View:

@using (Html.BeginForm("BookAdd", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" })) {     <input type="file" name="files[0]" id="files[0]" />     <input type="file" name="files[1]" id="files[1]" />     <input type="submit" value="Upload Book" /> } 

And here is an Action which should process uploaded file.

[HttpPost] public ActionResult BookAdd(IEnumerable<HttpPostedFileBase> files) {     // some actions     return View(); } 

The problem is that "files" always contains two elements which are null. What can be done to fix it?

It's time for some news. It seems like I found the problem, but I still don't know how to fix it. It appears that despite the fact I'm using "multipart/form-data" here:

@using (Html.BeginForm("BookAdd", "Admin", FormMethod.Post, new { enctype="multipart/form-data" })) {     <input type="file" name="File" id="file1" />     <input type="file" name="File" id="file2" />     <input type="submit" value="Upload Book" /> } 

Request.ContentType remains "application/x-www-forum-urlencoded" in controller..

like image 314
Roman Avatar asked Nov 16 '11 22:11

Roman


People also ask

What is HttpPostedFileBase in MVC?

The HttpPostedFileBase class is an abstract class that contains the same members as the HttpPostedFile class. The HttpPostedFileBase class lets you create derived classes that are like the HttpPostedFile class, but that you can customize and that work outside the ASP.NET pipeline.

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.


1 Answers

The problem is that the NAME of the field need to match with the controller parameter. In your case is "files"... so your name attribute should be "files" also.

like image 78
Romias Avatar answered Sep 23 '22 14:09

Romias