gpt4 book ai didi

javascript - 使用jquery.fileupload直接上传到amazon S3

转载 作者:行者123 更新时间:2023-11-27 23:59:53 39 4
gpt4 key购买 nike

在我的应用程序中,我希望能够将文件直接从浏览器上传到我的 AWS S3 存储桶。我的后端是 Rails,但我想避免到服务器的额外跳跃,并避免使用回形针、Carrierwave、Carrierwave_direct 等 gem ,以保持简单。我大致遵循这个tutorial来自heroku。

我正在使用 aws-sdk gem 和 jquery.fileupload.js 库。

问题是,当我尝试上传时,我从 AWS 收到了 400 错误请求。

我不认为这是 CORS 问题。我在我的存储桶上配置了 CORS,并且可以看到成功的 OPTIONS 请求,后跟文件上传的 POST 请求,该请求返回 400 错误请求。

以下是复制问题的简化演示。

这是 Controller 操作。它生成一个 AWS::S3::PresignedPost 对象,以便 View 可以使用它将文件直接发布到 S3。

  def new
Aws.config.update({
region: 'us-east-1',
credentials: Aws::Credentials.new('[FILTERED]', '[FILTERED]'),
})
s3 = Aws::S3::Resource.new
bucket = s3.bucket('mybucket')
@presigned_post = bucket.presigned_post(key: "attachments/#{SecureRandom.uuid}/${filename}")
@thing = Thing.new
end

这是 View ,new.html.erb,由上面的内容呈现,带有上传表单和处理上传的 javascript。

<div class='container'>
<%= form_for(@thing, html: { class: 'direct_upload' }) do |f| %>
<%= f.label 'Thing' %>
<%= f.file_field :attachment_url %>
<%= f.submit %>
<% end %>
</div>

<script type="text/javascript">
$(function() {
var $form = $('form.direct_upload'),
upload_url = '<%= escape_javascript(@presigned_post.url.to_s) %>',
upload_form_data = '<%= escape_javascript(@presigned_post.fields.to_json.html_safe) %>';

console.log('URL: ', upload_url);
console.log('Form data: ', upload_form_data);

if ($form.length) {
$form.find('input[type=file]').each(function(index, input) {
var $file_field = $(input);

$file_field.fileupload({
fileInput: $file_field,
url: upload_url,
type: 'POST',
autoUpload: false,
formData: upload_form_data,
paramName: 'file',
dataType: 'XML',

add: function(e, data) {
console.log('add callback fired.');
$form.submit(function(e) {
e.preventDefault();
console.log('form submitted.');
data.submit();
});
},
start: function(e) {
console.log('start callback fired');
},
done: function(e, data) {
console.log('done callback fired');
},
fail: function(e, data) {
console.log('fail callback fired');
console.log(e);
console.log(data);
}
});
});
}
});
</script>

这是从 S3 返回的响应:

<Error>
<Code>InvalidArgument</Code>
<Message>Bucket POST must contain a field named 'key'. If it is specified, please check the order of the fields.</Message>
<ArgumentName>key</ArgumentName>
<ArgumentValue></ArgumentValue>
<RequestId>[filtered]</RequestId>
<HostId>[filtered]</HostId>
</Error>

当页面加载时,您可以在 JavaScript 控制台中看到预期的输出:

URL:  https://mybucket.s3.amazonaws.com/
Form data: {"key":"attachments/d6313635-9735-4b84-9985-f9f62a036de8/${filename}","policy":"[FILTERED]","x-amz-credential":"[FILTERED]/us-east-1/s3/aws4_request","x-amz-algorithm":"AWS4-HMAC-SHA256","x-amz-date":"20150809T134239Z","x-amz-signature":"[FILTERED]"}

如您所见,有一个关键字段。

当您将文件添加到文件输入字段时,add 回调将按预期触发并绑定(bind)表单的提交操作。提交表单后,请求将转到 S3,但随后会触发 fail 回调,因为返回了 400。

这个question可能描述了问题是什么,但我无法根据提供的信息解决它。

以下是从 Chrome 开发工具复制的请求/响应信息。

Remote Address:54.231.17.17:443
Request URL:https://mybucket.s3.amazonaws.com/
Request Method:POST
Status Code:400 Bad Request

Response Headers
Access-Control-Allow-Methods:GET, POST, PUT
Access-Control-Allow-Origin:*
Connection:close
Content-Type:application/xml
Date:Sun, 09 Aug 2015 12:29:57 GMT
Server:AmazonS3
Transfer-Encoding:chunked
Vary:Origin, Access-Control-Request-Headers, Access-Control-Request-Method
x-amz-id-2:ymrt0MUlhf3bKqVWj+O5jhaUPXNEXy9HQh9PABmqzDkkb4Ods3Hy1LA++8G/Svri3LcOktpnGeE=
x-amz-request-id:545E755033D285F2

Request Headers
Accept:application/xml, text/xml, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:331
Content-Type:multipart/form-data; boundary=----WebKitFormBoundary9vtTme67oAg1OMyL
Host:braidio.s3.amazonaws.com
Origin:http://localhost:3000
Referer:http://localhost:3000/things/new
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36

Request Payload
------WebKitFormBoundary9vtTme67oAg1OMyL
Content-Disposition: form-data; name="file"; filename="my_text.txt"
Content-Type: text/plain


------WebKitFormBoundary9vtTme67oAg1OMyL--

如您所见,请求负载仅包含文件,而不包含 key 。该文件可能需要位于发布请求中的所有其他字段之后,这就是 S3 看不到关键字段的原因,如 answer 中所建议的。 .

一些相关的 gem :

* jquery-rails (4.0.4)
* rails (4.2.3)
* aws-sdk (2.1.13)
* aws-sdk-core (2.1.13)
* aws-sdk-resources (2.1.13)

还使用jquery.fileupload.js 5.42.3

我不知道如何让它发挥作用。

提前致谢!

最佳答案

我找到了解决方案。

我在前端捕获的后端生成的表单数据:

upload_form_data = '<%= escape_javascript(@presigned_post.fields.to_json.html_safe) %>'

必须从 JSON 字符串转换为 JavaScript 对象:

upload_form_data_obj = JSON.parse(upload_form_data);

显然,$.fileupload 函数需要一个 formData 对象,而不是字符串。

完成此更改后,所需的表单数据将包含在到 S3 的 POST 中,并且成功。

这是有效的 JavaScript 代码:

$(function() {
var $form = $('form.direct_upload'),
upload_url,
upload_form_data,
upload_form_data_obj;

if ($form.length) {
upload_url = '<%= escape_javascript(@presigned_post.url) %>'
upload_form_data = '<%= escape_javascript(@presigned_post.fields.to_json.html_safe) %>';
upload_form_data_obj = JSON.parse(upload_form_data);

console.log('URL: ', upload_url);
console.log('Form data: ', upload_form_data_obj);

$form.find('input[type=file]').each(function(index, input) {
var $file_field = $(input);
$file_field.fileupload({
fileInput: $file_field,
url: upload_url,
type: 'POST',
autoUpload: false,
formData: upload_form_data_obj, // needed to be an object, not a string
paramName: 'file',
dataType: 'JSON',

add: function(e, data) {
console.log('add callback fired.');
$form.submit(function(e) {
e.preventDefault();

console.log('form submitted.');
console.log(data);
data.submit();
});
},
start: function(e) {
console.log('start callback fired');
},
done: function(e, data) {
console.log('done callback fired');
},
fail: function(e, data) {
console.log('fail callback fired');
console.log(e);
console.log(data);
}
});
});
}
});

关于javascript - 使用jquery.fileupload直接上传到amazon S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904841/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com