简体   繁体   中英

Multiple file upload with JQuery and MVC4

I am trying to upload multiple files along with normal form data. This thing i have formerly implemented in PHP now i am using to do this in ASP.NET MVC4 in C#. I have an html form

<form action="/controller/actionane" name="applicationform" class="upload-form" method="post" onsubmit="return false;" enctype="multipart/form-data" id="userform"> 
        <input class="form-control" type="file" class="upload-file" data-max-size="12582912" multiple="multiple" name="attachment[]" value="documents">
        <input class="btn btn-success" type="submit" name="submit" onclick="formSubmit()" />
    </form>

My Javascript Code with jquery-1.11.1 looks like this:

    function formSubmit() {
    var form = $("form[name='applicationform']");
    var data = new FormData(form[0]);
    $.ajax(
        {
            method: "POST",
            url: form.attr("action"),
            processData: false, // Don't process the files
            contentType: false, cache: false, async: false,
            data: data,
            success: function (data) {
                alert(data);
            }
        });
    }

and my controller looks like this

[HttpPost]
public JsonResult submitApplication(HttpPostedFileBase[] attachment) 
{
                string fil= "";
                foreach (HttpPostedFileBase file in attachment)
                {
                    /*Geting the file name*/
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    fil += filename;
                    /*Saving the file in server folder*/
                    file.SaveAs(Server.MapPath("~/Images/" + filename));
                    string filepathtosave = "Images/" + filename;
                    /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
                }

                    return this.Json(fil,JsonRequestBehavior.AllowGet);
}

But this is not passing files to the parameter Object reference null exception is thrown What should I do to get this running?

You can try this:

Client Side Code:

<html>
<head>
<title>Upload Example</title>
<script src="~/Scripts/jquery-2.1.0.intellisense.js"></script>
<script src="~/Scripts/jquery-2.1.0.js"></script>
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<script>
$(document).ready(function () {
    $("#Upload").click(function () {
        var formData = new FormData();
        var totalFiles = document.getElementById("FileUpload").files.length;
        for (var i = 0; i < totalFiles; i++)
        {
            var file = document.getElementById("FileUpload").files[i];

            formData.append("FileUpload", file);
        }
        $.ajax({
            type: "POST",
            url: '/Home/Upload',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (response) {
                alert('succes!!');
            },
            error: function (error) {
                alert("Failed");
            }
        });
    });
});

</script>
</head>
<body>
<input type="file" id="FileUpload" multiple />
<input type="button" id="Upload" value="Upload" />
</body>
</html>

Server Side Code:

Server Side....

public class HomeController : Controller
{
  [HttpPost]
  public void Upload( )
  {
    for( int i = 0 ; i < Request.Files.Count ; i++ )
    {
      var file = Request.Files[i];
      var fileName = Path.GetFileName( file.FileName );
      var path = Path.Combine( Server.MapPath( "~/[Your_Folder_Name]/" ) , fileName );

      file.SaveAs( path );    
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM