Previously in another post, I had created a uploader using simple HTML and PHP to upload files directly to Amazon AWS S3 server. In this tutorial, we will just transform the form into Ajax based file uploader using jQuery. Ajax makes it really easy for the user as the page doesn’t need to be reloaded and we can also show a progress bar as the user waits for the upload to finish.
If you haven’t done that, you can take a look at the instructions I have provided in my previous post. This should be confusing at first but will get easy after few tries.
We must enable CORS (Cross-origin resource sharing) on our bucket to allows Ajax requests, otherwise, it is prohibited by default by the same-origin security policy. To enable CORS just go to your bucket permissions and click “CORS configuration” tab. You should be able to edit XML document containing CORS rules.
Now replace the XML document rules with your own, you can copy and paste XML rules I’ve provided below, just change the AllowedOrigin to your own domain name :
We only need to POST method for Ajax file upload, so <AllowedMethod>POST</AllowedMethod> should be adequate for now, you can allow more methods depending on your preferences.
Like in previous post, we create an HTML form using PHP. But this time we don’t need to specify success_action_redirect (Where AWS redirects upon successful upload), instead we use success_action_status with value set to 201, which returns the XML document as response, exactly what we need for our Ajax form.
Our HTML form is ready, let’s transofrom it to Ajax so that users don’t have to do full page refresh. In order to acomplish that we use jQuery.Ajax method, which provides us flexibility and core functionality of Ajax in jQuery.
As you can see the jQuery code is pretty straight forward, processData is set to false so that jQuery doesn’t mess-up the file data by converting it to string. contentType is also set to false, because jQuery will set wrong contentType and we end up with nasty AWS error. Lastly with the help of XHR object, we will create an upload progress bar to update the user about the progress.