Laravel TokenMismatchException and dropzone - javascript

I'm trying to upload pictures via dropzone, but I get tokenmismatch error even tho I added csrf token everywhere needed, i'm getting quite desperate...
My form
{!! Form::open(['route' => 'photo.upload', 'id' => 'hello', 'method' => 'POST', 'class' => 'dropzone no-margin dz-clickable']) !!}
<div class="dz-default dz-message"><span>Drop files here to upload</span></div></form>
{!! Form::close() !!}
my script
Dropzone.autoDiscover = false;
Dropzone.options.hello = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 5, // MB
parallelUploads: 2, //limits number of files processed to reduce stress on server
addRemoveLinks: true,
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content'),
},
accept: function(file, done) {
// TODO: Image upload validation
done();
},
sending: function(file, xhr, formData) {
// Pass token. You can use the same method to pass any other values as well such as a id to associate the image with for example.
formData.append("_token", $('input[name="_token"]').val() ); // Laravel expect the token post value to be named _token by default
},
init: function() {
this.on("success", function(file, response) {
// On successful upload do whatever :-)
});
}
};
// Manually init dropzone on our element.
var myDropzone = new Dropzone("#hello", {
url: $('#hello').attr('action')
});
Request headers
...
X-CSRF-Token:P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
...
Request Payload
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="_token"
P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="_token"
P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="file"; filename="Screen Shot 2016-01-14 at 18.27.40.png"
Content-Type: image/png
------WebKitFormBoundarySKMUFNO6dbgzeQVK--
and When I look in the generated form THERE IS the csrf field
<input name="_token" type="hidden" value="P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG">
Do you have any idea why it's not working even when I put crsf token where I should?
thank you for your time.

Simply place hidden field within your form like as
<input type="hidden" name="_token" value="{{csrf_token()}}">
You can make it different way by passing value of token using ajax call like as
$(function () {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
});

Instead of creating new element which is kinda dirty. You can just include it inside your manually init of dropzone.
var myDropzone = new Dropzone("#hello", {
url: $('#hello').attr('action'),
headers: {
'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
}
});
For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications

Related

How do I do this with javascript fetch

I was checking out this answer.
It's basically a request to Mailchimp to send a confirmation email to the user when they submit their email.
The code works perfectly with jquery. But I don't like jquery. And it's kind of annoying to have to add it just for this tiny snippet, since I won't be using it in the rest of my project. I already tried "translating" this into vanilla javascript using fetch but it doesn't seem to work.
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, do something to notify the user. maybe alert(data.msg);
} else {
// It worked, carry on...
}
}
});
}
EDIT
Some suggested I should add the HTML form:
I am doing all this because I want to send the user email to my MailChimp subscription list. But I want it to do it directly from my website without redirecting to the Mailchimp subscription page.
<form action="https://herokuapp.us5.list-manage.com/subscribe/post-json?u=070e69e5e3e6e664a8066e48f&id=0bf75ac6c4&c=?" method="get" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate newsletter__form" target="_blank">
<label for="mce-EMAIL">Ingresa tu correo electrónico:</label>
<input type="email" placeholder="ejemplo#gmail.com" value="" name="EMAIL" class="required textfield email__textfield" id="mce-EMAIL">
<input type="submit" value="suscribirme" name="subscribe" id="mc-embedded-subscribe" class="button raise">
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_070e69e5e3e6e664a8066e48f_0bf75ac6c4" tabindex="-1" value=""></div>
</form>
I also found out jquery ajax method get accepts the data argument but it takes what's inside of the data and adds it to the URL. So it's still a get request with no body. I am trying to find a way to do that but with fetch but somehow the jquery URL has things I don't know where they come from. I also tried doing this with POST method and fetch but apparently, the server doesn't allow that.
For what is worth this is how the URL generated by jquery request looks like:
https://herokuapp.us5.list-manage.com/subscribe/post-json?u=070e69e5e3e6e664a8066e48f&id=0bf75ac6c4&c=jQuery35105022544193369527_1633147928440&EMAIL=email123456%40gmail.com&b_070e69e5e3e6e664a8066e48f_0bf75ac6c4=&_=1633147928441
And this is how I can trick my URL to look like with fetch. Here I get a CORS error
https://herokuapp.us5.list-manage.com/subscribe/post-json?u=070e69e5e3e6e664a8066e48f&id=0bf75ac6c4&c=?&EMAIL=paula.uzcategui68%40gmail.com&b_070e69e5e3e6e664a8066e48f_0bf75ac6c4=
And this is what I'm doing with fetch
function register(form) {
data = new FormData(form);
data = Object.fromEntries(data);
data = Object.entries(data);
let arroba = /#/gi;
let action = form.getAttribute("action")+ "&"+ data[0][0] +"="+ data[0][1].replace(arroba, '%40') + "&" + data[1][0] + "=" + data[1][1]
// console.log(action)
fetch(action, {
method: 'get',
cache: 'no-cache',
headers: {
'content-type': 'application/json; charset=utf-8'
},
})
.then(response => response.json())
.catch(error => {
alert("Could not connect to the registration server. Please try again later."+ error)
});
}
Try this, it is the exact solution for your question (I hope). If you still get stuck please comment down, I will explain.
async function register(form) {
let data = new FormData(form);
data = JSON.stringify(Object.fromEntries(data)); // convert formdata to json
let response = await fetch(form.action, {
method: form.method,
body: data,
cache: 'no-cache',
headers: {
'content-type': 'application/json; charset=utf-8'
}
})
.then(response => response.json())
.catch(error => {
alert("Could not connect to the registration server. Please try again later.")
});
}

How to post multiple files with fetch API?

I'm trying to post multiple files from an input using fetch API but form data remains empty after appending
I looked at the answers here, here, here, here and here and tried them all to no avail
Am using the Laravel framework for the backend, here's my Blade view file
<meta name="csrf-token" content="{{ csrf_token() }}">
<input class="form-control" type="file" id="pro-image" name="image[]" multiple onchange="submit()">
<script>
function submit() {
var ins = document.getElementById('pro-image').files.length;
var fd = new FormData();
for (var x = 0; x < ins; x++) {
fd.append("pro-image[]", document.getElementById('pro-image').files[x]);
}
console.log(fd);
fetch('/', {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content
},
method: 'POST',
credentials: "same-origin",
body: fd,
});
}
</script>
The console logs an empty form data object
And this is the code in the backend
Route::post('/', function () {
dd(request()->all());
});
In which I consequently get an empty array
Really can't tell why this isn't working! Any idea as to what am doing wrong?
Remove your Content-Type: application/json header, or set it to multipart/form-data instead.

Stripe with Google App Engine - Upload image directly through browser using Javascript for Mananaged Account Identity Verification

Hi I've been searching for ages about how to upload directly from the browser, as is suggested in the case of using Stripe with Google App Engine at this forum. Also the Stripe documentation suggests it is possible to upload directly from a browser as is suggested here.
I have been trying with AJAX but from my effort and research it seems it is not possible to get the path to the local file because of security reasons. The code below shows the closest I've gotten, however I don't know how to upload an image through the browser without it touching the server. The console returns an error of "Invalid file: must be uploaded in a multipart/form-data request".
Next I will try using Jquery Form Plugin, however I don't know if I will have any success with that.
var formData = new FormData($('#theHTMLForm')[0]);
var sendarray={purpose:"identity_document", file:formData};
sendarray=JSON.stringify(sendarray);
$.ajax({
type:'POST',
url: 'https://uploads.stripe.com/v1/files',
data: sendarray,
mimeType: "multipart/form-data",
headers: {
"Authorization": "Bearer STRIPEPUBLISHABLEKEY"
},
contentType: 'application/json',
processData: false,
success:function(data){
alert('success');
console.log(data);
},
error: function(data){
alert('error');
console.log(data);
}
});
Thanks to a very kind person on this forumn, I was able to make it work!! I'll copy the answer here just in case anybody comes by looking for the same answer.
HTML
<div>
<form method="post" id="fileinfo" name="fileinfo" ajax="true">
<input type="file" id="file-box" name="file" required />
<input type="submit" value="Upload" />
</form>
</div>
<div>
<div id='label-results'>...</div>
<pre id="upload-results"></pre>
</div>
And Javascript
$('#fileinfo').submit(function(event) {
event.preventDefault();
var data = new FormData();
var publishableKey = 'pk_test_***';
data.append('file', $('#file-box')[0].files[0]);
data.append('purpose', 'identity_document');
$.ajax({
url: 'https://uploads.stripe.com/v1/files',
data: data,
headers: {
'Authorization': 'Bearer ' + publishableKey
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
}).done(function(data) {
$('#label-results').text('Success!');
$('#upload-results').text(JSON.stringify(data, null, 3));
}).fail(function(response, type, message) {
$('#label-results').text('Failure: ' + type + ', ' + message);
$('#upload-results').text(JSON.stringify(response.responseJSON, null, 3));
});
return false;
});

How to update XML file using Ajax + Jquery?

I want to update the XML file using Ajax & jquery. I am new to ajax so tried with using both POST/PUT.
For PUT: I am getting the error 405. i.e "Method Not Found"
For POST: Bad Request
vvmsUrl: is the path to xml file
Our get is working fine, but not the PUT/POST.
PUT Code:
vvmsUrl: is the path to xml file
var XMLData= "<origin>ABCbfk</origin>";
jQuery.ajax({
type: "PUT",
url: vvmsUrl,
contentType: "application/xml",
headers: { 'Prefer' : 'persistent-auth',
'Access-Control-Allow-Methods': 'PUT'},
dataType: "xml",
processData: false,
crossDomain: true,
data: XMLData,
success:function(msg)
{
alert("hello"+msg);
},
error: function(msg){
alert("Error"+msg);
LOG(xhr.status);
}
});
I am stuck from 2 days. I am not getting what goes wrong in this.
You can try : upload any file
HTML code
<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />
Javascript code
<script>
var client = new XMLHttpRequest();
function upload()
{
var file = document.getElementById("uploadfile");
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
client.open("post", "/upload", true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
}
/* Check the response status */
client.onreadystatechange = function()
{
if (client.readyState == 4 && client.status == 200)
{
alert(client.statusText);
}
}
</script>
You need a server side script to handle modifications to anything at the server you cannot just use client side jQuery. The script will also check who is authorized to write to the file or otherwise anyone can modify/update your XML file which is a security problem and probably is what you don't want.
Please could you include all of your code? I mean what is vvmUrl ? Are you using some web service? Is your code making call to another domain, why crossDomain: true?
EDIT:
This should work in jQuery 1.7.2+
var username = 'myUser';
var password = 'myPassword';
$.ajax
({
type: "PUT",
url: vvmsUrl,
contentType: 'application/xml',
async: false,
crossDomain: true,
username: username,
password: password,
data: xmlData,
success: function (){
alert('Works!');
}
});

File Upload without Form

Without using any forms whatsoever, can I just send a file/files from <input type="file"> to 'upload.php' using POST method using jQuery. The input tag is not inside any form tag. It stands individually. So I don't want to use jQuery plugins like 'ajaxForm' or 'ajaxSubmit'.
You can use FormData to submit your data by a POST request. Here is a simple example:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).
All answers here are still using the FormData API. It is like a "multipart/form-data" upload without a form. You can also upload the file directly as content inside the body of the POST request using xmlHttpRequest like this:
var xmlHttpRequest = new XMLHttpRequest();
var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);
Content-Type and Content-Disposition headers are used for explaining what we are sending (mime-type and file name).
I posted similar answer also here.
UPDATE (January 2023):
You can also use the Fetch API to upload a file directly as binary content (as also was suggested in the comments).
const file = ...file handle...
const fileName = ...file name...
const target = ...target...
const mimeType = ...mime type...
const promise = fetch(target, {
method: 'POST',
body: file,
headers: {
'Content-Type': mimeType,
'Content-Disposition', `attachment; filename="${fileName}"`,
},
},
});
promise.then(
(response) => { /*...do something with response*/ },
(error) => { /*...handle error*/ },
);
See also a related question here: https://stackoverflow.com/a/48568899/1697459
Step 1: Create HTML Page where to place the HTML Code.
Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.
Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajax Code url apply which one on your php file name.
JS
//$(document).on("change", "#avatar", function() { // If you want to upload without a submit button
$(document).on("click", "#upload", function() {
var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
url: "/upload_avatar", // Upload Script
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
// Do something after Ajax completes
}
});
});
HTML
<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />
Php
print_r($_FILES);
print_r($_POST);
Basing on this tutorial, here a very basic way to do that:
$('your_trigger_element_selector').on('click', function(){
var data = new FormData();
data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
// append other variables to data if you want: data.append('field_name_x', field_value_x);
$.ajax({
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
url: your_ajax_path,
dataType : 'json',
// in PHP you can call and process file in the same way as if it was submitted from a form:
// $_FILES['input_file_name']
success: function(jsonData){
...
}
...
});
});
Don't forget to add proper error handling
Try this puglin simpleUpload, no need form
Html:
<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>
Javascript:
$('#simpleUpload').simpleUpload({
url: 'upload.php',
trigger: '#enviar',
success: function(data){
alert('Envio com sucesso');
}
});
A non-jquery (React) version:
JS:
function fileInputUpload(e){
let formData = new FormData();
formData.append(e.target.name, e.target.files[0]);
let response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
let result = await response.json();
console.log(result.message);
}
HTML/JSX:
<input type='file' name='fileInput' onChange={(e) => this.fileInput(e)} />
You might not want to use onChange, but you can attach the uploading part to any another function.
Sorry for being that guy but AngularJS offers a simple and elegant solution.
Here is the code I use:
ngApp.controller('ngController', ['$upload',
function($upload) {
$scope.Upload = function($files, index) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
file: file,
url: '/File/Upload',
data: {
id: 1 //some data you want to send along with the file,
name: 'ABC' //some data you want to send along with the file,
},
}).progress(function(evt) {
}).success(function(data, status, headers, config) {
alert('Upload done');
}
})
.error(function(message) {
alert('Upload failed');
});
}
};
}]);
.Hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-controller="ngController">
<input type="button" value="Browse" onclick="$(this).next().click();" />
<input type="file" ng-file-select="Upload($files, 1)" class="Hidden" />
</div>
On the server side I have an MVC controller with an action the saves the files uploaded found in the Request.Files collection and returning a JsonResult.
If you use AngularJS try this out, if you don't... sorry mate :-)

Categories

Resources