【问题标题】:React Native - S3 Pre-signed URL upload issues. cURL works, fetch doesn't - 403 SignatureDoesNotMatchReact Native - S3 预签名 URL 上传问题。 cURL 有效,提取无效 - 403 SignatureDoesNotMatch
【发布时间】:2022-01-01 23:16:55
【问题描述】:

如标题所示,我可以毫无问题地从 lambda 获取预签名 URL。该 URL 在 cURL 中可以毫无问题地上传图像,也可以与测试 python 脚本一起使用。

我一生都无法弄清楚为什么这在 javascript 中不起作用(特别是 React Native,在 Expo 中)。

这里大致是感兴趣的代码:

const getBlob = async (fileUri) => {
    const resp = await fetch(fileUri);
    const imageBody = await resp.blob();
    
    return imageBody;
  };


async function putPhoto(photoURI){
// code to get the S3URL

    const imageBlob = await getBlob(photoURI)

    response = await fetch(S3URL,{
            method: "PUT",    
            body: imageBlob,
            // headers: {
            //     "Content-Type": "application/json"
            // }
         
        })

这尤其令人抓狂,因为来自 S3 的响应包含 URL,我可以显式地 cURL 并成功解析:

curl -X PUT -T .\test.jpg "https://<bucketname>.s3.amazonaws.com/<lambda generated hash>.jpg?AWSAccessKeyId=<>&x-amz-security-token=<>&Expires=<>"

当然,在 中替换了“敏感数据”。

我唯一能看到其他人有共同问题的地方是标题 - 我也尝试过输入:

headers: {}

我认为这会覆盖我忘记的任何全局标头范围。

有什么建议吗?非常感谢。

【问题讨论】:

    标签: javascript react-native rest amazon-s3 pre-signed-url


    【解决方案1】:

    好的,看起来 S3 在获取 fetch() 请求时非常具体地需要正确的标头,并且不关心来自 cURL 的相同标头。或者至少,在这种情况下需要为 fetch 进行设置。

    用于 lambda 的 Python 代码:

    url = boto3.client('s3').generate_presigned_url(
            ClientMethod='put_object', 
            Params={'Bucket': BUCKET_NAME, 'Key': full_id, 'ContentType': 'application/octet-stream'},
            ExpiresIn=3600
        )
    

    如图所示添加 Content-Type 参数至关重要。

    另外,将我上面的代码更改为(参见 Content-Type):

    async function putPhoto(photoURI){
    // code to get the S3URL
    
        const imageBlob = await getBlob(photoURI)
    
        response = await fetch(S3URL,{
                method: "PUT",    
                body: imageBlob,
                headers: {
                    "Content-Type": "application/octet-stream"
                }
             
            })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2018-07-10
      相关资源
      最近更新 更多