尝试使用Ajax上传文件时,ASP NET Core MVC操作返回错误请求

时间:2019-07-19 09:13:59

标签: c# ajax asp.net-core

我遇到以下问题。

当我尝试使用ajax从局部视图的表单中上传2个文件时,我得到了 响应代码400错误的请求

我已经检查过我发送了AntiForgeryToken,但是它仍然会产生此错误。

动作

 [HttpPost]
 public async Task<IActionResult>UploadFile([FromBody]ApplicationsFileCreateInputModelcreateInputMode)
        {
            var fileId = await applicationFileService.UploadAsync(createInputModel);

            return Json(fileId);
        }

局部视图

@using ArkStore.App.Models.BindingModels.ApplicationFiles
@model ApplicationsFileCreateInputModel

    <form enctype="multipart/form-data" method="post">
        <div class="custom-file w-50 mb-2">
            <label class="custom-file-label" asp-for="AppApk"></label>
            <input class="custom-file-input" asp-for="AppApk" id="appApk" type="file">
            <span asp-validation-for="AppApk" class="text-danger"></span>
        </div>

        <div class="custom-file w-50 mb-2">
            <label class="custom-file-label" asp-for="Thumbnail"></label>
            <input class="custom-file-input" asp-for="Thumbnail" id="thumbnail" type="file">
            <span asp-validation-for="Thumbnail" class="text-danger"></span>
        </div>

        <div class="form-group">
            <button id="upload" type="submit" class="btn btn-primary">Upload</button>
        </div>
    </form>

Ajax函数


function setUploadFileId() {

    $.post({
        url: "https://localhost:44377/Applications/UploadFile",

        data: {
            "data": new FormData(document.forms[1]), 
            "__RequestVerificationToken": "@Context.GetAntiforgeryToken()"
             },

        contentType: false,

        processData: false,

        success: function (id) {

            $("#fileId").val(id);
        },
        error: function (error)
        {
           console.log(error);
        }

    });

}

$("#upload").on("click",
    function (evt) {
        evt.preventDefault();
        setUploadFileId();
    });

ApplicationFileCreateInputModel

public class ApplicationsFileCreateInputModel
    {
        [Required]
        [Display(Name = "Upload Thumbnail file")]
        public IFormFile Thumbnail { get; set; }

        [Required]
        [Display(Name = "Upload Apk")]
        public IFormFile AppApk { get; set; }
    }

它包含2个IFormFile属性

1 个答案:

答案 0 :(得分:0)

尝试将ajax函数更改为以下代码:

@section Scripts{ 
<script>
    function setUploadFileId() {
        var fileInput1 = $('#appApk')[0];
        var file1 = fileInput1.files[0];
        var fileInput2 = $('#thumbnail')[0];
        var file2 = fileInput2.files[0];

        var formData = new FormData();
        formData.append("appApk", file1);
        formData.append("thumbnail", file2)

        $.ajax(
            {
                url: "https://localhost:44377/Applications/UploadFile",
                data: formData,
                processData: false,
                contentType: false,
                type: "POST",
                success: function (data) {
                    alert("Files Uploaded!");
                }
            }
        );

    }

    $("#upload").on("click",
        function (evt) {
            evt.preventDefault();
            setUploadFileId();
        });

</script>
}

如果在发布操作中添加[ValidateAntiForgeryToken]属性,则需要添加防伪验证时,需要从标头发送RequestVerificationToken。

1。在表单代码中添加@Html.AntiForgeryToken()

2。在ajax中添加标头:

$.ajax({
    type: "POST",
    //...
    headers: {
        RequestVerificationToken:
            $('input:hidden[name="__RequestVerificationToken"]').val()
    }, 
    //...
});

请参阅Submitting Fom Returns 400 Status