本文介绍了如何通过jQuery Ajax将AntiForgeryToken(CSRF)与FormData一起发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想通过AJAX与AntiForgeryToken一起POST fileUpload.这是我的代码:

So I want to POST fileUpload along with AntiForgeryToken via AJAX. Here's my code :

查看

@using (Html.BeginForm("Upload", "RX", FormMethod.Post, new {id = "frmRXUpload", enctype = "multipart/form-data"}))
{
     @Html.AntiForgeryToken()
     @Html.TextBoxFor(m => m.RXFile, new {.type = "file"})
     ...rest of code here
}

<script>
    $(document).ready(function(){
        $('#btnRXUpload').click(function () {
            var form = $('#frmRXUpload')

            if (form.valid()) {
                var formData = new FormData(form);
                formData.append('files', $('#frmRXUpload input[type="file"]')[0].files[0]);
                formData.append('__RequestVerificationToken', fnGetToken());

                $.ajax({
                    type: 'POST',
                    url: '/RX/Upload',
                    data: formData,
                    contentType: false,
                    processData: false
                })
            }
        })
    })
</script>

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload()
{
    //rest of code here
}

我知道

提琴手出错.知道如何解决这个问题吗?

error via fiddler. Any idea how to solve this issue?

我找到了答案:

<script>
        $(document).ready(function(){
            $('#btnRXUpload').click(function () {
                var form = $('#frmRXUpload')

                if (form.valid()) {
                    var formData = new FormData(form.get(0)); //add .get(0)
                    formData.append('files', $('#frmRXUpload input[type="file"]')[0].files[0]);

                    $.ajax({
                        type: 'POST',
                        url: '/RX/Upload',
                        data: formData,
                        contentType: false,
                        processData: false
                    })
                }
            })
        })
    </script>

推荐答案

最终找到了答案:

我只需要在表单中添加.get(0),这是代码:

I just need to add .get(0) in the form, here's the code :

<script>
        $(document).ready(function(){
            $('#btnRXUpload').click(function () {
                var form = $('#frmRXUpload')

                if (form.valid()) {
                    var formData = new FormData(form.get(0)); //add .get(0)
                    formData.append('files', $('#frmRXUpload input[type="file"]')[0].files[0]);
                    //formData.append('__RequestVerificationToken', fnGetToken()); //remark this line

                    $.ajax({
                        type: 'POST',
                        url: '/RX/Upload',
                        data: formData,
                        contentType: false,
                        processData: false
                    })
                }
            })
        })
    </script>

这篇关于如何通过jQuery Ajax将AntiForgeryToken(CSRF)与FormData一起发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:52