5. Uploading using XHR
Introduction
5.1. Enabling CORS for the Amazon S3 Bucket
When submitting files via an XMLHttpRequest (XHR, sometimes referred to as Ajax) to Amazon S3, you'll need to enable cross-origin resource sharing (CORS) for your bucket. Otherwise, you will run into an error when you try to upload a file. To set this up, log in to the AWS console and navigate to the Permissions tab, and click the CORS configuration button, as shown below.By default, a single
CORSRule
element is configured, allowing GET requests to be made via any domain. The upload form uses POST requests, so a new CORSRule
block needs to be added here. Add the following code below the existing CORSRule
element, just before the closing CORSConfigruation
tag, and press the blue Save button.
<CORSRule>
<AllowedOrigin>http://yourdomain</AllowedOrigin>
<AllowedMethod>POST</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
NOTE
Be sure to replace the
AllowedOrigin
element value with your own domain. It will work for local domains likehttp://yourapp.dev
if you are using Valet or Homestead. If you prefer, you can add a wildcard*
to support POST requests from any domains, but in production it's recommended that you restrict it to your application's domain.
With CORS configured for your bucket, you are now ready to start using XHR to upload files.