3

This is my View

Test Upload File

<form action="@Url.Action("Index", "Home")" method="post" enctype="multipart/form-data">
    @Html.AntiForgeryToken()
    <label for="file">Filename:</label>
    <input type="file" name="files" id="files" />

    <input type="submit" name="submit" value="Upload" />
</form>

This is my Controller

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
          { 
              if (files != null)
                {
                 foreach (var file in files)
                   {
                    try
                     {
                      if (file != null && file.ContentLength > 0)
                        {
                          var fileName = file.FileName;
                          var path = Path.Combine(Server.MapPath(@"\Upload"), fileName);
                          file.SaveAs(path);

                          ViewBag.Message = "File uploaded successfully";
                         }
                       }
                      catch (Exception ex)
                      {
                        ViewBag.Message = "ERROR:" + ex.Message.ToString();
                       }
                   }
                 }
               return View();
             }

The problem is the HttpPostedFileBase files is always null. I cant find the problem.

enter image description here

halfer
  • 19,824
  • 17
  • 99
  • 186
User123
  • 71
  • 1
  • 3
  • 12
  • Possible duplicate of [HttpPostedFileBase always return null in ASP.NET MVC](http://stackoverflow.com/questions/8551528/httppostedfilebase-always-return-null-in-asp-net-mvc) – HudsonPH Aug 02 '16 at 07:30
  • Change your file input name attribute. `input file tag name` attribute and `HttpPostedFileBas argument name` should not be same – mmushtaq Aug 02 '16 at 07:33
  • issue on this http://stackoverflow.com/questions/8551528/httppostedfilebase-always-return-null-in-asp-net-mvc is about name input type file. – User123 Aug 02 '16 at 07:33
  • did you mean this name="files"? @user55 i already change to different name, but still not working. – User123 Aug 02 '16 at 07:38
  • @user55 please show me how.. – User123 Aug 02 '16 at 07:48
  • then you can try `Form onsubmit` method.. – mmushtaq Aug 02 '16 at 07:52
  • maybe you can show me how to using _Form onsubmit_ @user55 – User123 Aug 02 '16 at 08:26
  • 1
    The code you have shown works fine and the parameter will not be `null`. Do you have any javascript involved? –  Aug 02 '16 at 08:50
  • @Wawa i debugged your code. its working fine. – mmushtaq Aug 02 '16 at 09:17
  • i didnt involve any javascript. it should be fine, but i dont know why it always null. i didnt see any mistake in my code. @StephenMuecke – User123 Aug 02 '16 at 09:36
  • thanks for your effort. really appreciate that. it should be working. I dont no where else need to change to make it works. @user55 – User123 Aug 02 '16 at 09:38
  • i check on immediate window, it show `this.Request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"` means that it doesnt post right ContentType. – User123 Aug 02 '16 at 09:50
  • What are you trying to post? – mmushtaq Aug 02 '16 at 09:52
  • @user55 i tried to upload file which post `multipart/form-data"` – User123 Aug 02 '16 at 10:04

2 Answers2

2

Here is an example how to use form onsubmit method

Your HTML part

<form id="formTest" method="post" enctype="multipart/form-data">

        <label for="file">Filename:</label>
        <input type="file" name="files" id="files" />

        <input type="submit" name="submit" value="Upload" />
    </form>


script

<script type="text/javascript">
var form = document.getElementById('formTest').onsubmit = function (e) {
        e.preventDefault();
    var formdata = new FormData(); //FormData object
    var fileInput = document.getElementById('files');
    if (fileInput != "" && fileInput.files.length > 0) {
        //Iterating through each files selected in fileInput
        for (i = 0; i < fileInput.files.length; i++) {
            //Appending each file to FormData object
            formdata.append(fileInput.files[i].name, fileInput.files[i]);
        }
        //Creating an XMLHttpRequest and sending
        var xhr = new XMLHttpRequest();

           var url = '@Url.Action("Index","Home")';
        xhr.open('POST', url);
        xhr.send(formdata);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;

            }
        }
        return false;
    }
}
</script>


C#

public ActionResult Index()
{ 
   if (Request.Files.Count > 0)
   {
      var file = Request.Files[0];    
      if (file != null && file.ContentLength > 0)
      {
         var fileName = Path.GetFileName(file.FileName);
         var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
         file.SaveAs(path);
      }
    return View();

   }
}
mmushtaq
  • 3,430
  • 7
  • 30
  • 47
  • i had tried using your solution above, it work perfectly. thank you so much. But why is my normal upload file (not involve javascript) is not working? is it possible not to use javascript? @user55 – User123 Aug 02 '16 at 10:15
  • My pleasure. As i mentioned your code is working perfectly at my machine without using any JavaScript. – mmushtaq Aug 02 '16 at 10:30
  • If it solved your problem, then please mark it as answer, so others will not post answer to this question anymore.. – mmushtaq Aug 02 '16 at 11:21
0

You can also handle files with Request.Files like this:

public ActionResult Index()
{ 
   if (Request.Files.Count > 0)
   {
      var file = Request.Files[0];    
      if (file != null && file.ContentLength > 0)
      {
         var fileName = Path.GetFileName(file.FileName);
         var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
         file.SaveAs(path);
      }
   }
}

And for your second question, please try to use it between Html.BeginForm instead of form like this:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <label>Filename:</label>
    <input type="file" name="file1"/>
    <input type="submit" name="submit" value="Upload" />
}
kkakkurt
  • 2,790
  • 1
  • 30
  • 33
  • I don't know why, but its still not working. The Request.Files.Count is always 0. I have to use normal html form instead of using html helper. – User123 Aug 02 '16 at 07:59
  • Is it possible to arise from input's id and label for attribute? Can you try it without input "id" and label without "for"? – kkakkurt Aug 02 '16 at 08:34
  • 1
    `@using (Html.BeginForm("Index", "Fax", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() }` i change it to this. but its still not working. – User123 Aug 02 '16 at 08:47