使用AJAX发送带有JSON信息的文件

本文关键字:JSON 信息 文件 AJAX 使用 | 更新日期: 2023-09-27 18:21:52

我有一个ASP.NET c#页面,它将以JSON格式发布带有AJAX的表单信息。该信息包括Texboxes的文本和Dropdownlists的值等。

此外,我还需要发送一个文件。

我已经尝试了以下代码,它运行良好:

                $(".popup-content input:text,.popup-content textarea").each(function () { // Fill object by inputs
                    objInputs[$(this).attr("name")] = $(this).val();
                });
                $.ajax({ //Post information
                    type: "POST",
                    url: "myAjax.aspx",
                    data: { func: "Create", information: JSON.stringify(objInputs) /* Convert object to JSON string */ },
                    success: function (data) { // if sending was successful try to send file
                                var files = $("#fileImage").get(0).files; //get files form uploadfile
                                if (files.length > 0) {
                                    var data = new FormData();
                                    data.append(files[0].filename, files[0]);
                                    $.ajax({ //Send file
                                        type: "POST",
                                        url: "Handler1.ashx",
                                        contentType: false,
                                        processData: false,
                                        data: data,
                                        success: function (data) {
                                        },
                                        error: function (xhr, ajaxOptions, thrownError) {
                                            alert(xhr.status + " " + thrownError);
                                        },
                                    });
                             }
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status + " " + thrownError);
                    },
                });

但现在我想知道是否有一种方法可以将我的文件和JSON一起发送?

使用AJAX发送带有JSON信息的文件

我找到了解决方案。Jquery代码应该更改为如下内容:

<script>
        $(document).ready(function () {
            $(document).on("click", "#submit", function () {
                var objInputs = {};
                objInputs["id"] = "12";
                $("#form1 input:text").each(function () { // Fill object by inputs
                    objInputs[$(this).attr("name")] = $(this).val();
                });
                var formData = new FormData();
                formData.append("information", JSON.stringify(objInputs));
                var files = $("#fileupload").get(0).files; //get files form uploadfile
                if (files.length > 0) {
                    for (var i = 0; i < files.length; i++) {
                        //add each file to the form data and iteratively name them
                        formData.append("file-" + i, files[i]);
                    }
                    $.ajax({ //Send file
                        type: "POST",
                        url: "Handler1.ashx",
                        contentType: false,
                        processData: false,
                        data: formData,
                        success: function (data) {
                            alert(data)
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert(xhr.status + " " + thrownError);
                        },
                    });
                }
            });
        });
    </script>

以及处理发送的数据的C#代码(Handler1.ashx):

    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.Files.Count > 0) //To handling files
        {
            HttpFileCollection files = context.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                if ((files[i].ContentLength < 500000) && (files[i].ContentType == "image/jpeg"))
                {
                    HttpPostedFile file = files[i];
                    string fname = context.Server.MapPath("~/Images/" + file.FileName);
                    file.SaveAs(fname);
                }
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("File Uploaded Successfully!");
        }
        if (!string.IsNullOrEmpty(context.Request["information"])) //To handeling JSON
        {
            string JSON = context.Request["information"]; //JSON String
        }
    }