I'm doing some front-end stuff for a Rails app and I don't get to mess with the backend architecture. Basically, I'm supposed to allow users to upload a file and make that submission essentially go straight to Amazon through a form handled by CarrierWave. If you've ever tried to do this same thing with ajax, you'll know it's virtually impossible.
That puts me here: I need to be able to call .submit()
on an html form element and then hook into the progress of the upload as if I were listening for the "progress" event on an XMLHttpRequest.
Forgive me for not showing tons of code. I'm really just looking for two very simple things.
form.addEventListener('progress', function () {...})
? (<- That doesn't work, by the way.)I don't think you can get progress on the upload on a standard form submit.
So I haven't tested this, but why not submit the form via AJAX? You can upload files with a FormData
object, which can handle multipart requests for uploads.
Something like this might work:
// grab the form you want to submit.
var formElement = document.getElementById("myFormElement");
// make an xhr object
var request = new XMLHttpRequest();
// track progress
request.upload.addEventListener('progress', progressHandler, false);
// setup request method and url
request.open("POST", formElement.action);
// send the request
request.send(new FormData(formElement));
You would have to listen for the server response and do what it tells you, redirect or handle failures or whatever. But I think it should work. The server you are submitting to probably doesn't care if it's a xhr request or a standard browser request.
And it should work in all modern browsers.
See docs on FormData
.
And here's a link to that details how to track progress on ajax uploads.
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