带有ID的jQuery Ajax上传文件 [英] jQuery ajax upload file with id

查看:80
本文介绍了带有ID的jQuery Ajax上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET MVC5.我的目标是使用jQuery ajax上传文件.成功后,在表中返回上载文件的部分视图.当我逐步执行jQuery代码时,id和文件是正确的,但是当执行Action时,两个参数均为null.这是我的代码:

Im using ASP.NET MVC5. My goal was to upload file using jQuery ajax. When successful, return a partial view of the uploaded files in a table. When I step through the jQuery code, the id and files are correct, but when stepped into Action, both parameters are null. Here are my codes:

控制器的动作:

[HttpPost]
        public ActionResult AddAttachments(string id, IEnumerable< HttpPostedFileBase> files)
        {            
            if (files != null)
            {
                //save files
            }
            var cardKey = db.CardKeys.Single(s => s.CardKeyID == Convert.ToInt32(id));
            var attachments = cardKey.Request.Attachments;
            return PartialView("_AttachmentsTable",attachments);
        }

jQuery:

$(function () {
    var table = $("#attachmentTable").DataTable();
    var path = MySettings.addAttachmentURL;
    $("#btnAddAttachment").click(function (event) {
        event.preventDefault();

        var formData = new FormData();
        var cardKeyID = $("#CardKeyID").val();

        var formData = $.each($("#files")[0].files, function (i, file) {
            formData.append('file-' + i, file);
        });
        console.log("formData = " + formData);
        $.ajax({
            type: "POST",
            url: path,
            contentType: false,
            processData:false,
            cache:false,
            data: {id:cardKeyID,files: formData },
            success: function (partialResult) {
                $("#tableData").html(partialResult);
                table = $("#attachmentTable").DataTable();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $("#message").html(JSON.stringify(jqXHR).toString());
                alert("AJAX error: " + textStatus + ' : ' + errorThrown);
            }
        });
    });
});

剃刀视图:

<fieldset>
            <legend>Add Attachments</legend>
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    @Html.Label("File Upload", new { @class = "control-label col-md-6" })
                    <div class="col-md-6">
                        <input type="file" id="files" name="files" multiple/><br />
                        <input type="submit" id="btnAddAttachment" value="Add Attachment"/>

                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    @Html.Label("File Description", new { @class = "control-label col-md-6" })
                    <div class="col-md-6">
                        @Html.TextBox("FileDescription")
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    @Html.Label("Comment", new { @class = "control-label col-md-6" })
                    <div class="col-md-6">
                        @Html.TextBox("Comment")
                    </div>
                </div>
            </div>
        </div>
        <div id="tableData">
            @Html.Partial("_AttachmentsTable",Model.Request.Attachments)
        </div>
        </fieldset>

推荐答案

问题是因为您需要直接将FormData提供给$.ajaxdata属性,而不是在对象内,因为它将被编码.如果您需要向请求中添加数据,请将其附加到FormData对象:

The issue is because you need to provide FormData directly to the data property of $.ajax, not within an object as it will be encoded. If you need to add data to the request, append it to the FormData object:

var formData = new FormData();
var cardKeyID = $("#CardKeyID").val();
var formData = $.each($("#files")[0].files, function (i, file) {
    formData.append('file-' + i, file);
});
formData.append('id', cardKeyID);

$.ajax({
    data: formData,
    // other properties here...
});

然后在控制器中,您需要直接从Request检索数据:

Then in the controller you need to retrieve the data directly from the Request:

[HttpPost]
public ActionResult AddAttachments()
{    
    var id = Request.Params["id"];
    foreach(var file in Request.Files) {
        //save files
    }

    var cardKey = db.CardKeys.Single(s => s.CardKeyID == Convert.ToInt32(id));
    var attachments = cardKey.Request.Attachments;
    return PartialView("_AttachmentsTable",attachments);
}

请注意,如果form元素包含要在请求中发送的所有字段,则可以避免使用$.each,而不必直接附加即可,只需使用:

Note that if the form element contains all fields that you want to send in the request, you can avoid the $.each and having to append directly and simply use:

var formData = new FormData($('form')[0]);

这篇关于带有ID的jQuery Ajax上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆