Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use AntiforgeryToken with dropzone.js and MVC 5 with Vanilla JS?

I'm stuck at the moment trying to figure out how can I send the antiforgery token using Dropzone.js and vanilla javascript (no jQuery).

This is my initialization code at the moment:

$(document).ready(function (e) {
        var myDropzone = new Dropzone("#myDropzone", { url: "/Media/AjaxUpload", maxFilesize: 10, addRemoveLinks: true, maxFiles: 1 });
        myDropzone.on("success", function (response) {
            //Do some personal stuff.
        });
        myDropzone.on("sending", function (xhr, formData) {
            formData["__RequestAntiForgeryToken"] = document.getElementsByName("__RequestVerificationToken")[1].value
        });

    });

I have tried appending the token to no avail on Dropzone's sending event, even at the header. Any suggestions on how to achieve this?

like image 889
Jose A Avatar asked Aug 29 '15 15:08

Jose A


1 Answers

I think you nearly nailed it there on the first go, Jose. The small mistake you made was missing an argument in the event handler function.

From the Dropzone documentation:

Called just before each file is sent. Gets the xhr object and the formData objects as second and third parameters, so you can modify them (for example to add a CSRF token) or add additional data.

The event arguments are actually file, xhr, formData, and if you include all three then you can manipulate the form successfully. The advantage of doing things this way is that there is no need to create a custom attribute, just use the ValidateAntiForgeryToken attribute.

myDropzone.on("sending", function (file, xhr, formData) {
    formData["__RequestAntiForgeryToken"] = document.getElementsByName("__RequestVerificationToken")[1].value;
});

I have tested this with a slightly different implemetation than your's, and it works nicely.

like image 100
David Kirkland Avatar answered Sep 22 '22 23:09

David Kirkland