简体   繁体   English

使用JQuery和MVC4上载多个文件

[英]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#. 我以前曾在PHP中实现过这个东西,现在我正在C#中的ASP.NET MVC4中使用它来实现。 I have an html form 我有一个HTML表单

<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: 我的带有jquery-1.11.1的Javascript代码如下所示:

    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? 但这不是将文件传递给参数。对象引用将引发null异常怎么办才能使它运行?

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 );    
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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