尝试使用DropZone JS上传文件时,服务器响应400代码

时间:2019-04-26 17:33:23

标签: c# asp.net-mvc asp.net-core-mvc dropzone.js nopcommerce-4.1

我正在尝试使用Dropzone JS上传文件,但收到错误消息:

  

服务器响应400条代码”

我尝试在表单中设置@Html.AntiForgeryToken()。我还尝试发送令牌:

xhr.setRequestHeader("XSRF-$('input:hidden[name="__RequestVerificationToken"]').val());

但仍然出现相同的错误。

我的HTML:

<form enctype="multipart/form-data" method="POST">
    @Html.AntiForgeryToken()
    <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: "/Admin/Product/UploadFiles",
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    maxFiles: 100,
    //acceptedFiles: "image/*",

    init: function () {

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

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

        this.on("addedfile", function (file) {

            var removeButton = Dropzone.createElement("<button class='btn btn-lg dark'>Remove File</button>");

            removeButton.addEventListener("click", function (e) {
                // Make sure the button click doesn't submit the form:
                e.preventDefault();
                e.stopPropagation();
                wrapperThis.removeFile(file);
            });

            file.previewElement.appendChild(removeButton);
        });

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

我的动作

[HttpPost]
public ActionResult UploadFiles()
{
    var postedUsername = Request.Form["Username"].ToString();

    // process files

    return Json(new { status = true, Message = "Account created." });
}

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案,在sendingmultiple事件中,代码应该是

formData.append("__RequestVerificationToken",
                $('input:hidden[name="__RequestVerificationToken"]').val());