使用Faraday将文件上传到S3

时间:2015-11-05 20:30:34

标签: ruby amazon-web-services file-upload amazon-s3 faraday

我试图将文件上传到我的S3存储桶。我在下面用凭据设置了我的请求。我无法推断出标题和正文中的内容。秘密访问密钥在签名内。我错过了什么?

  def params
    {
      :key => key_prefix + file_name, 
      :aws_access_key_id => access_key_id,
      :acl => "private",
      :policy => encoded_policy,
      :signature => encoded_signature
    }
  end

  def headers
    {
      "Content-Type" => mime_type,
      "x-amz-security-token" => session_token
    }
  end

  def upload
    connection.post do |req|
      req.headers = headers
      req.body = params.to_json
    end
  end

  def connection
    Faraday.new(:url => bucket_url) do |builder|
      builder.request :multipart
      builder.request :url_encoded
      builder.adapter :typhoeus
    end
  end

我收到的错误是:

<Error><Code>PreconditionFailed</Code><Message>At least one of the pre-conditions you 
specified did not hold</Message><Condition>Bucket POST must be of the enclosure-type 
multipart/form-data</Condition>

1 个答案:

答案 0 :(得分:2)

好问题!我碰到了同样的事情。

包含文件的困难部分。这似乎有效:

  def params
    {
      :key => key_prefix + file_name, 
      :aws_access_key_id => access_key_id,
      :acl => "private",
      :policy => encoded_policy,
      :signature => encoded_signature
      :file => Faraday::UploadIO.new(StringIO.new(<<FILECONTENTS>>), <<MIMETYPE>>)
    }
  end