使用 Faraday 上传文件到 S3
Upload file to S3 using Faraday
我正在尝试将文件上传到我的 S3 存储桶。下面我用凭据设置了我的请求。我无法推断 headers 和 body 中应该包含什么。秘密访问密钥在签名中。我错过了什么?
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>
好问题!我运行变成了同样的东西。
其中最难的部分是包含文件。这似乎有效:
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
我正在尝试将文件上传到我的 S3 存储桶。下面我用凭据设置了我的请求。我无法推断 headers 和 body 中应该包含什么。秘密访问密钥在签名中。我错过了什么?
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>
好问题!我运行变成了同样的东西。
其中最难的部分是包含文件。这似乎有效:
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