小编典典

ASP.NET MVC中的Ajax FileUpload和JQuery formData

ajax

我在发布formData到服务器端操作方法时遇到了一些问题。因为ajax调用不会将文件发送到服务器,所以我必须formData手动添加文件上传器数据,如下所示:

var formData = new FormData();
formData.append("imageFile", $("#imageFile").file);
formData.append("coverFile", $("#coverFile").file);

我编写了jQuery函数,该函数需要使用ajax调用将表单数据发布到服务器。它有效,但formData在服务器端发布的内容始终为空!

这是我的脚本:

    <script>
        function SubmitButtonOnclick()
        {    
            var formData = new FormData();
            formData.append("imageFile", $("#imageFile").file);
            formData.append("coverFile", $("#coverFile").file);

            $.ajax({
                type: "POST",
                url: '@Url.Action("EditProfile", "Profile")',
                data: formData,
                dataType: 'json',
                contentType: "multipart/form-data",
                processData: false,
                success: function (response) {
                    $('#GeneralSection').html(response.responseText);
                },
                error: function (error) {
                    $('#GeneralSection').html(error.responseText);
                }
            });
        }
    </script>

编辑1: 这是控制器中的操作方法:

        public ActionResult EditProfile(ProfileGeneralDescription editedModel,
                                HttpPostedFileBase imageFile,
                                HttpPostedFileBase coverFile,
                                string postOwnerUser)
        {
            try
            {
                if (postOwnerUser == User.Identity.Name)
                {
                // edit codes...    
                    var result = GetProfileGeneralDescription(postOwnerUser);
                    return PartialView("_GeneralProfile", result);
                }
                else
                {
                    var error = new HandleErrorInfo(
                    new Exception("Access Denied!"),
                    "Profile",
                    EditProfile
                    return PartialView("~/Views/Shared/Error.cshtml", error);
                }
            }
            catch (Exception ex)
            {
                var error = new HandleErrorInfo(ex, "Profile", EditProfile
                return PartialView("~/Views/Shared/Error.cshtml", error);
            }
        }

编辑2: cshtml查看文件内容:

@model Website.Models.ViewModel.Profile

    @using (Ajax.BeginForm("EditProfile", "Profile", new { postOwnerUser = User.Identity.Name }, new AjaxOptions()
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "GeneralSection"
    }, new { enctype = "multipart/form-data" }))
    {

        <div>
             <button id="btnSubmit" type="button" onclick="SubmitButtonOnclick()">Submit</button>
        </div>

        <input type="hidden" name="username" id="username" value="@Model.Username"/>

        <fieldset>
            <legend>Edit Photos</legend>
            <div>
                Select profile picture:
                <input id="imageFile" type="file" name="imageFile" accept="image/png, image/jpeg" />
                @Html.CheckBoxFor(modelItem => modelItem.DefaultCover)<span>Remove profile photo</span>
            </div>
            <div>
                Select cover picture:
                <input id="coverFile" type="file" name="coverFile" accept="image/png, image/jpeg" />
                @Html.CheckBoxFor(modelItem => modelItem.DefaultCover)<span>RemoveCover</span>
            </div>
        </fieldset>
    }

任何提示,链接或代码示例都将很有用。
先感谢您!


阅读 343

收藏
2020-07-26

共1个答案

小编典典

您可以使用Jquery Ajax代替

 <script>
            function SubmitButtonOnclick()
            { 
                var formData= new FormData();
                var imagefile=document.getElementById("imageFile").files[0];
                var coverfile=document.getElementById("coverFile").files[0];
                formData.append("imageFile",imageFile);
                formData.append("coverFile",coverFile);
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "/Profile/EditProfile", true);
                xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
                xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
                xhr.send(formData);

            }

      function UploadComplete(evt) {
        if (evt.target.status == 200) 
                alert("Logo uploaded successfully.");

        else 
                 alert("Error Uploading File");
        }

    function UploadFailed(evt) {
        alert("There was an error attempting to upload the file.");

    }
 </script>

这对我有用!

您的脚本有变化

 function SubmitButtonOnclick() {
        var formData = new FormData();
        var file = document.getElementById("imageFile").files[0];
        var file1 = document.getElementById("coverFile").files[0];
        formData.append("imageFile", file);
        formData.append("coverfile", file1);
        $.ajax({
            type: "POST",
            url: '@Url.Action("EditProfile","Default1")',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (response) {
                $('#GeneralSection').html(response.responseText);
            },
            error: function (error) {
                $('#GeneralSection').html(error.responseText);
            }
        });
    }
2020-07-26