使用签名 URL 上传到 Amazon S3 适用于 curl,但不适用于 javascript [英] Uploading to Amazon S3 using a signed URL works with curl but not in javascript

查看:29
本文介绍了使用签名 URL 上传到 Amazon S3 适用于 curl,但不适用于 javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PUT 请求将文件上传到 Amazon S3.我使用 boto 生成我的签名网址.如果我这样做

I'm trying to upload a file to Amazon S3 using a PUT request. I generate my signed urls using boto. If I do

curl --upload-file test.jpg $SIGNED_URL

然后上传工作正常(因此签名网址没有问题).我还使用 curl 将引用设置为各种内容,它仍然有效,所以我认为也不存在 CORS 问题.我正在尝试使用 javascript 上传文件 blob,如下所示:

then the upload works fine (so there's not an issue with the signed urls). I've also set the referer to various things with curl and it still works, so I don't think there is a CORS issue either. I'm trying to upload a file blob using javascript as follows:

var xmlhttp = new XMLHttpRequest();    
xmlhttp.open("PUT", $SIGNED_URL);
xmlhttp.setRequestHeader('Content-Type', blob.type);
xmlhttp.send(blob);

这总是返回 403 Forbidden 错误.我发现很难在网上找到任何关于将数据从 javascript 发送到 S3 的信息.我现在意识到 POST 表单数据更常见,但有什么方法可以修改我正在做的事情吗?

This always returns a 403 Forbidden error. I'm finding it surprisingly difficult to find any information online about PUTing data to S3 from javascript. I realize now that it's more common to POST form data, but is there any way to modify what I'm doing to also work?

我现在找到了错误的正文:

I've found the body of the error now:

> <Error><Code>SignatureDoesNotMatch</Code> <Message>The request
> signature we calculated does not match the signature you provided.
> Check your key and signing method.</Message>

因此,签名似乎是问题所在.同样,当我将它与 curl 一起使用时(即使它在 javascript 中失败),同样的确切 url 也有效.

So it appears that the signing is the issue. Again, the same exact url works when I use it with curl (even after it's failed in javascript).

推荐答案

问题是 curl 未发送的Content-Header".无论您是否明确添加,Chrome 都会发送此标头.要获得可与此标头一起使用的签名网址,您需要将 headers={'Content-Type':type} 传递给 boto 中的 generate_url.

The issue was the 'Content-Header' which curl was not sending. Chrome sends this header regardless of whether you add it explicitly. To get a signed url that will work with this header you need to pass headers={'Content-Type':type} to generate_url in boto.

这篇关于使用签名 URL 上传到 Amazon S3 适用于 curl,但不适用于 javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆