Direct Upload on S3 throws error : No 'Access-Control-Allow-Origin' header is present on the requested resource
2
Not solved Solved
almost 2 years ago

Hi everybody, I have been trying to implement direct upload to S3 on my app following these instructions : https://devcenter.heroku.com/articles/direct-to-s3-image-uploads-in-rails

So I have a form where the user can upload a picture and it looks like this with the code provided in the tutorial :

<%= form_for(@hotel,  url: account_hotels_path(params[:account_id]), html: { class: 'directUpload', data: { 'form-data' => (@s3_direct_post.fields), 'url' => @s3_direct_post.url, 'host' => URI.parse(@s3_direct_post.url).host } }) do |f| %>
  <%= f.hidden_field :account_id, :value => params[:account_id] %>
  <div class="form-group">
    <%= f.label :city %>
    <%= f.text_field :city %>
  </div>
  <div class="form-group">
    <%= f.label :postcode %>
    <%= f.text_field :postcode %>
  </div>
  <div class="form-group">
    <%= label_tag "Number of rooms" %>
    <%= number_field_tag "room_number"%>
  </div>
  <div class="form-group">
    <%= label_tag "Number of Beds in each room" %>
    <%= number_field_tag "bed_number"%>
  </div>
  <div class="field">
    <%= f.label "Photo" %><br>
    <%= f.file_field "photo[image_url]" %>
  </div>
   <div class="form-group">
    <%= f.submit %>
  </div>
<% end %>  
<% content_for(:after_js) do %>
  <script>
   $('.directUpload').find("input:file").each(function(i, elem) {
      var fileInput    = $(elem);
      var form         = $(fileInput.parents('form:first'));
      var submitButton = form.find('input[type="submit"]');
      var progressBar  = $("<div class='bar'></div>");
      var barContainer = $("<div class='progress'></div>").append(progressBar);
      fileInput.after(barContainer);
      console.log(form);
      console.log(form.data('form-data'));
      console.log(form.data('url'));
      console.log(fileInput)
      fileInput.fileupload({
        fileInput:       fileInput,
        url:             form.data('url'),
        type:            'POST',
        autoUpload:       true,
        formData:         form.data('form-data'),
        paramName:        'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
        dataType:         'XML',  // S3 returns XML if success_action_status is set to 201
        replaceFileInput: false,
        progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        progressBar.css('width', progress + '%')
      },
      start: function (e) {
        submitButton.prop('disabled', true);

        progressBar.
          css('background', 'green').
          css('display', 'block').
          css('width', '0%').
          text("Loading...");
      },
      done: function(e, data) {
        submitButton.prop('disabled', false);
        progressBar.text("Uploading done");

        // extract key and generate URL from response
        var key   = $(data.jqXHR.responseXML).find("Key").text();
        var url   = '//' + form.data('host') + '/' + key;

        // create hidden field
        var input = $("<input />", { type:'hidden', name: fileInput.attr('name'), value: url })
        form.append(input);
      },
      fail: function(e, data) {
        submitButton.prop('disabled', false);

        progressBar.
          css("background", "red").
          text("Failed");
      }
      });
    });
  </script>
<% end -%>

However when my user uploads a file I get the following error :

XMLHttpRequest cannot load https://quickbed.s3-eu-west-1.amazonaws.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

I know this error might be due to the CORS configuration of my bucket but I have updated it according to the tutorial instructions :

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>http://localhost:3000</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

What is going wrong here ? If some of you want to gain some extra points on SO, it's here :

http://stackoverflow.com/questions/35318110/direct-upload-on-s3-throws-error-no-access-control-allow-origin-header-is-pr

almost 2 years ago

looks like localhost:3000 is not accepted by s3 with direct upload...? Try with ngrok to see if you get the same error @davidgeismar

almost 2 years ago

@krokrob it doesnt work better with ngrock :(. I still get the same error I also tried to change my CORS config on my bucket to : <AllowedOrigin>*</AllowedOrigin>

Cancel
Submit your answer