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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With