使用Rails和jQuery文件上载将Content-Type设置为直接上传到S3

sup*_*ng7 11 jquery content-type ruby-on-rails amazon-s3 jquery-file-upload

我在这个主题上看到了很多问题,但是我遇到的任何问题对我都有用,所以我在这里发布另一个......

我正在Ruby on Rails上尝试使用jQuery File Upload插件直接配置文件上传到Amazon S3 .我跟着非常有用的Heroku教程来完成初始设置.文件上传很好,但是它们都标记为Content-Type: binary/octet-streamS3,所以当它们在应用程序中提供时,所有文件都会下载而不是直接打开.

这是一个问题,因为我试图允许图像,PDF,音频或视频文件,所以我需要能够Content-Type从文件中获取正确的文件并将其传递给S3.在看在亚马逊AWS的-SDK文档宝石,我看到这一节有关添加.where(:content_type).starts_with("")到presigned后对象的末尾修改政策.但是,当我这样做时,它引发了一个错误:

<Error><Code>AccessDenied</Code>
<Message>Invalid according to Policy: Policy Condition failed: ["starts-with", "$Content-Type", ""]</Message>
Run Code Online (Sandbox Code Playgroud)

所以我添加content_type: ""了预先签名的post对象的opts哈希,现在它再次工作,但是所有文件默认为binary/octet-stream默认的所有文件默认为image/jpeg.这是我现在的代码:

调节器

def new
  @s3_direct_post = S3_BUCKET.presigned_post(
                  key: "uploads/#{SecureRandom.uuid}/${filename}",
                  success_action_status: 201,
                  acl: :public_read,
                  content_type: "").where(:content_type).starts_with("")
end
Run Code Online (Sandbox Code Playgroud)

_form.html.haml

:javascript
  $(function() {
    $('.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);
      var fd           = #{@s3_direct_post.fields.to_json.html_safe};
      fileInput.after(barContainer);
      fileInput.fileupload({
        // This 'add' section is where I thought to set the Content-Type, but I've tried  with and without it and Content-Type remains the same on S3
        add: function (e, data) {
          fd["Content-Type"] = data.files[0].type;  
          console.log(fd);    // The JSON object shows Content-Type correctly in console
          data.submit();
        },  
        fileInput:        fileInput,
        url:              '#{@s3_direct_post.url}',
        type:             'POST',
        autoUpload:       true,
        formData:         fd,   // My updated JSON object
        paramName:        'file',
        dataType:         'XML',
        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   = 'https://d295xbrl26r3ll.cloudfront.net/' + key.replace(/ /g, "%20");

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

          progressBar.
            css("background", "red").
            text("Failed");
        }
      });
    });
  });
Run Code Online (Sandbox Code Playgroud)

如何Content-Type正确发送到S3?

小智 15

用以下内容替换添加块:

      fd["Content-Type"] = data.files[0].type;  
      data.formData = fd;
      data.submit();
Run Code Online (Sandbox Code Playgroud)

回调是正确的,但data.formData已经采用了原始版本的fd.只需使用修改过的fd再次设置它就可以了.

更新控制器方法,所以你不要两次:

@s3_direct_post = S3_BUCKET.presigned_post(
                  key: "uploads/#{SecureRandom.uuid}/${filename}",
                  success_action_status: 201,
                  acl: :public_read).where(:content_type).starts_with("")
Run Code Online (Sandbox Code Playgroud)