ASP.Net MVC使用MultiFile.js上传文件时遇到问题

时间:2016-11-01 21:22:35

标签: c# jquery asp.net asp.net-mvc

当我将文件上传到ASP.Net MVC时,我正在使用MultiFile.js库。 http://www.fyneworks.com/jquery/multifile/

问题是当我在其间添加一个java脚本监听器来捕获JSON返回值时,我在ASP中的函数将文件视为null。如果我不使用java脚本,一切都按预期工作。我想知道我需要做些什么来改变我在java脚本中所做的事情,这样ASP仍然会收到我试图上传的文件。

下面的行显示了参数附件的空值:

public ActionResult AttachFiles(IEnumerable<HttpPostedFileBase> attachments)

Java脚本

$("#attachBtn").on("click", function (e) {
    $(".has-success").removeClass("has-success");
    $(".has-danger").removeClass("has-danger");
    e.preventDefault();

    const frm = $("#attachFiles");
    $.post(frm.attr("action"), frm.serialize(), function (data) {
        if (data.success) {
            $("#alertMessage").addClass("alert-success");
            $("#alertMessage #alertMessageText").text(data.message);
        } else {
            $("#alertMessage").addClass("alert-danger");
            $("#alertMessage #alertMessageText").text(data.message);
        }
    });
});

$("#multiFileCustom").MultiFile({
    list: "#attachmentList"
});

ASP.Net MVC

[HttpPost]
public ActionResult AttachFiles(IEnumerable<HttpPostedFileBase> attachments)
{
    if (attachments == null || attachments.FirstOrDefault() == null)
    {
        return this.Json(new { success = false, message = "No files to attach" }, JsonRequestBehavior.AllowGet);
    }

    userAttachments = new List<string>();

    foreach (var file in attachments)
    {
        if (file.ContentLength == 0)
        {
            continue;
        }

        var fullPath = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\uploads\" + Path.GetFileName(file.FileName);
        file.SaveAs(fullPath);
        userAttachments.Add(fullPath);
    }

    return this.Json(new { success = true, message = "Files Attached" }, JsonRequestBehavior.AllowGet);
}

HTML

@using (Html.BeginForm("AttachFiles", "Home", FormMethod.Post, new { @id = "attachFiles", enctype = "multipart/form-data" }))
{
    <div class="row">
        <div class="form-group">
            <label class="col-sm-1">Attach:</label>
            <div class="col-sm-11">
                <input type="file" id="multiFileCustom" name="attachments" />
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-offset-1" id="attachmentList"></div>
    </div>

    <div class="row">
        <div class="col-sm-2 col-lg-offset-1">
            <input type="submit" id="attachBtn" class="btn btn-default" value="Attach" />
        </div>
    </div>
}

1 个答案:

答案 0 :(得分:0)

异步文件上传无法与Controller一起使用。您可以使用Generic Handler实现此目的。

还有其他方法可以使用控制器

1.首先安装

Install-Package BeginCollectionItem

2.关注我的代码

控制器

 public class FileUploadViewModel
    {
        [Required]
       public HttpPostedFileBase File { get; set; }
        //Other Model Property
    }
    public class FileUploadMutipleController : Controller
    {
        //
        // GET: /FileUploadMutiple/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult AttachFiles(IEnumerable<FileUploadViewModel> attachments)
        {
            //Do other stuffs
            return View();
        }
        [HttpPost]//For generating multiple file attachment
        public ActionResult GetFile()
        {
            return PartialView("~/Views/FileUploadMutiple/_File.cshtml", new FileUploadViewModel());
        }
    }

_File.cshtml

@model MvcApplication1.Controllers.FileUploadViewModel

<tr>
    @using (Html.BeginCollectionItem("attachments"))//Name of ListName to bind
    {
        <td>
        @Html.TextBoxFor(m => m.File, new { type = "file" })
        @Html.ValidationMessageFor(m => m.File)
        </td>
        <td>
            <button type="button" id="removeProductRow" class="btn btn-primary" onclick="removeDetailRow(this)">
                Remove</button>
        </td>
    }
</tr>

和Index.cshtml

@{
    ViewBag.Title = "Index";
    //Layout = null;
}
<script src="@Url.Content("~/Scripts/jquery-2.1.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $('#add-file').click(function () {
           // alert('Hi');
            $.ajax({
                url: '@Url.Action("GetFile")',
                type: 'POST',
                success: function (data) {
                    console.log(data);
                    $('#tbl > tbody:last').append(data);
                    //$('.new-recipeingredients').append(data);
                }
            });
            return false;
        });

    });
    function removeDetailRow(element) {
        var detailRow = $(element).closest('tr');
        $(detailRow).remove();
    }
</script>
<h2>Index</h2>
@using (Html.BeginForm("AttachFiles", "FileUploadMutiple", FormMethod.Post, new { @id = "attachFiles", enctype = "multipart/form-data" }))
{
     @Html.ValidationSummary(true)
     <a id="add-file" class="btn btn-success" href="javascript:void(0);">Add another</a>
    <table id="tbl">
        <thead>
        <tr>
            <th>
                File
            </th>
            <th>
                Upload
            </th>

        </tr>
        </thead>
        <tbody>


        </tbody>


    </table>
    <input type="submit" id="attachBtn" class="btn btn-default" value="Attach" />
}