尝试直接将文件上传到amazon S3存储桶时请求失败

时间:2016-02-10 09:35:15

标签: ruby-on-rails file-upload amazon-s3 bucket

我正在尝试按照以下说明在我的应用上实施直接上传到amazonS3: https://devcenter.heroku.com/articles/direct-to-s3-image-uploads-in-rails

我在S3上创建了一个存储桶并下载了凭据。在本教程之后,我在rails应用程序中添加了一个初始化程序:

Aws.config.update({
  region: 'Ireland',
  credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']),
})

S3_BUCKET = Aws::S3::Resource.new.bucket(ENV['S3_BUCKET'])

我在我的hotel_controller上设置了一个before_action:

  before_action :set_s3_direct_post, only: [:new, :edit, :create, :update]

  private

   def set_s3_direct_post
    @s3_direct_post = S3_BUCKET.presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: '201', acl: 'public-read')
  end

我已经用适当的JS定制了我的表单:

<%= 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 -%>

我也按照教程中的建议更改了我的存储桶的CORS设置。

但是每次我开始上传文件时,请求都会失败,我得到:

query.self-c64a74367bda6ef8b860f19e74df08927ca99d2be2ac934e9e92d5fd361e0da4.js?body=1:10244 OPTIONS https://quickbed.s3.ireland.amazonaws.com/ net::ERR_NAME_NOT_RESOLVED

enter image description here

这里出了什么问题?

1 个答案:

答案 0 :(得分:1)

$(document).ready(function(){ var strFiles = 'SC2RFFBCRMEPOSAPP20131022.csv|SC2RFFBDEALERSORO20131022.csv|SC2ROFUOR00_ESHOP20131026.csv|SC2ROFUOR00_ESHOP20131027.csv|SC2ROFUOR00_ESHOP20131028.csv|SC2RFSFCRMEPOSAPP20131022.csv|SC2RFSFDEALERSORO20131022.csv|SC2ROSFWEBSHOPAPP20131022.csv|SC2RFRPCRMEPOSAPP20131022.csv|SC2RFRPDEALERSORO20131022.csv|SC2RORPOR00_ESHOP20131022.csv|SC2RORPWEBSHOPAPP20131022.csv|Active_range_20131022.csv|Active_range_20131023.csv|Active_range_20131024.csv|SC2ROZBOR00_SLRM_20131019(1).csv|SC2ROZBOR00_SLRM_20131019.csv' ; var arrFiles = strFiles.split('|'); var strFileType = {Full:5,Scope:3,Proposal:4,ActiveRange:3,ForceValue:2} ; var pragcycle = 0; var step = 0 ; var increment = 0; var i = 0 $("#loadfiles").click(function(){ var array=[] //Maybe set-up your progressbar here for (key in strFileType) { step = 100 / strFileType[key]; pragcycle = pragcycle + strFileType[key]; increment = 0; for (i;i<pragcycle;i++) { array.push(arrFiles[i]); } } recursivefunction(0,array); }); function recursivefunction(index,array) { if((index!=array.length)&&(array.length!=0)) { $.ajax({ url: "/quickadmin/php/admin/pages/AppLoadCSV.php", data: "basename=" + array[index], success: function (data) { //Updating your progressbar and stuff increment = increment + step; $("." + key).attr("style","width: " + increment + "%"); recursivefunction(index+1,array); } }); } else { //You are finished } } 不是一个有效的区域,在这里你需要......这是一个区域端点。

您正在寻找Ireland

http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region