I’m working on a piece of code using the Stripe Connect API where the user can send a visual from an input type="file"
to an AJAX call via jQuery, this way:
var form_file = new FormData();
form_file.append('file', document.querySelector('input#file_to_send').files[0]);
When the user submits the form, I copy the visual in a folder on my server via PHP and keep its name in a session variable.
If something is incorrect or missing in the form, the user goes back to the same page, where the visual is shown in a img
element under the input type="file"
one, so the user knows that their visual has been taken into consideration.
After that, I need to do send the file in an AJAX call again… Except that this time, the file cannot be selected from the input type="file"
anymore, the only accessible source I have would be to take it’s name from the img
element in JavaScript.
Now, if I do this:
var form_file = new FormData();
form_file.append('file', $('img#visual').attr('src'));
And send this via the same AJAX call:
$.ajax({
url: 'https://uploads.stripe.com/v1/files',
type: 'POST',
processData: false,
contentType: false,
headers: {'Authorization': 'Bearer xxxxxxxxxxxxxxxxx' },
data: form_file
}).fail(function(e) {
console.log('fail: ' + e);
}).done(function(e) {
console.log('file uploaded: ' + e.id);
});
My question, you guessed it, is: is there a way to/how should I do to send a file not from an input
element as a source, but a defined path taken from an img
element?
2
Answers
I was able to achieve what I wanted! Here is the code I ended up with:
I added a console.log() at each step of this if anyone needs this code and wants to see the result of what is happening step by step. The steps being:
After that, it can be sent via ajax to the Stripe API.
I read your question a second time. If I understand correctly you need to send a cross-domain AJAX request to stripe.com, so you are not controlling the PHP code on the server side, right?
SHORT ANSWER:
The easiest way would be to do your form check in Javascript instead of PHP, so you won’t need to go back and "lose" the selected input file.
… BUT if you really need/want to send a cross-domain file using only its URL,
then you’ll need to convert Data URI to File then append to FormData :
1/ Get you image base64 value
2/ Convert the base64 image to Blob :
3/ Send you Blob with FormData :
Sources :
Edit:
You could speed up phase 1 and 2 by using the Fetch API to get the image Blob directly.
(WARNING: not compatible with IE)
Source : How to get a File() or Blob() from an URL in javascript?