Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpPostedFileBase always return null in ASP.NET MVC

I have a problem when I upload a file in ASP.NET MVC. My code is below:

View:

@{     ViewBag.Title = "Index";     Layout = "~/Views/Shared/_Layout.cshtml"; }  <h2>Index2</h2> @using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" })) {   <input type="file" />   <input type="submit" /> } 

Controller:

[HttpPost] public ActionResult FileUpload(HttpPostedFileBase uploadFile) {     if (uploadFile != null && uploadFile.ContentLength > 0)     {         string filePath = Path.Combine(Server.MapPath("/Temp"), Path.GetFileName(uploadFile.FileName));         uploadFile.SaveAs(filePath);     }     return View(); } 

But uploadFile always returns null. Can anyone figure out why??

like image 932
Joshua Son Avatar asked Dec 18 '11 11:12

Joshua Son


2 Answers

@{     ViewBag.Title = "Index";     Layout = "~/Views/Shared/_Layout.cshtml"; }  <h2>Index2</h2> @using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" })) {   <input type="file" name="uploadFile"/>   <input type="submit" /> } 

you have to provide name to input type file to uploadFile in order to model binding work in ASP.net mvc and
also make sure that name of your input type file and argument name of HttpPostedFileBase is identical.

like image 119
dotnetstep Avatar answered Nov 12 '22 23:11

dotnetstep


I had tried most of the solutions posted online for this topic, but found it better to use a workaround instead..

It really didn't matter what I did the HttpPostedFileBase and/or HttpPostedFile were always null. Using the HttpContext.Request.Files collection seemed to work with no hassles at all.

e.g.

 if (HttpContext.Request.Files.AllKeys.Any())         {             // Get the uploaded image from the Files collection             var httpPostedFile = HttpContext.Request.Files[0];              if (httpPostedFile != null)             {                 // Validate the uploaded image(optional)                  // Get the complete file path                 var fileSavePath =(HttpContext.Server.MapPath("~/UploadedFiles") + httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf(@"\")));                  // Save the uploaded file to "UploadedFiles" folder                 httpPostedFile.SaveAs(fileSavePath);             }         } 

In the above example I only grab the first file, but it is just a matter of looping though the collection to save all files.

HTH

Rob

like image 25
roblem Avatar answered Nov 13 '22 00:11

roblem