剃须刀页面上的 Dropzone returns 400 状态代码

Dropzone on razor Page returns 400 status code

我在 ASP.NET 核心 2.0 中的 RAZOR 页面上使用 DropZone 以及像这样的其他表单输入 -

DzDemo.cshtml 页 -

<form method="post" enctype="multipart/form-data">
    <input type="text" id="Username" name="Username" />
    <div class="dropzone" id="my-dropzone" name="mainFileUploader">
        <div class="fallback">
            <input name="file" type="file" multiple />
        </div>
    </div>
</form>
<div>
    <button type="submit" id="submit-all"> upload </button>
</div>

JS:-

Dropzone.options.myDropzone = {
            url: "/DzDemo?handler=Upload",
            autoProcessQueue: false,
            uploadMultiple: true,
            parallelUploads: 100,
            maxFiles: 100,
            acceptedFiles: "image/*",
           // paramName: myParamName,
            init: function () {

                var submitButton = document.querySelector("#submit-all");
                var wrapperThis = this;

                submitButton.addEventListener("click", function () {
                    wrapperThis.processQueue();
                });

                this.on('sendingmultiple', function (data, xhr, formData) {
                    formData.append("UserName", $("#Username").val());
                });
                this.on('error',
                    function (file, response) {
                        console.log(response);
                        alert(response);
                    });
            }
        };

DzDemo.cshtml.cs 页面:-

[HttpPost]
        public IActionResult OnPostUpload()
        {
            var data = Request.Form; //This is 
            return Page();
        }

但我从服务器收到 400 响应,我无法在服务器端处理上传的文件它也不会在服务器端热 Upload 方法。请帮忙

将 dropzone.js 与 Razor Pages 一起使用会导致 400 的一件事是,如果表单中缺少 AntiforgeryToken。

这通常会自动注入,但删除 _viewimports 或其 taghelper 会阻止这种情况。

要验证,只需将此行添加到 <form/> 元素内或查看调试控制台以获取错误消息。

@Html.AntiForgeryToken()

在 sendingmultiple 添加这一行,它会解析你的 pb:

this.on('sendingmultiple', function (data, xhr, formData) {
    xhr.setRequestHeader("XSRF-TOKEN",
                     $('input:hidden[name="__RequestVerificationToken"]').val());
});

我通过设置 headers 选项使它工作

headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }

当然,您需要在 <form /> 元素或在页面中明确添加 @Html.AntiForgeryToken()