【问题标题】:Retrofit - Upload Image to S3 using presigned URL改造 - 使用预签名 URL 将图像上传到 S3
【发布时间】:2020-04-27 19:41:56
【问题描述】:

我从 Lambda 获取预签名 URL,但不知道为什么当我向生成的 URL 发出 PUT 请求时,我的图像没有上传到 S3。

我完全遵循了这两个答案,但它仍然不适合我

https://stackoverflow.com/a/46177449/11110509

https://stackoverflow.com/a/46579224/11110509

谁能指出我做错了什么?

public interface IUploadImages{
   @PUT
   Call<String> listRepos(@Url String url, @Body RequestBody image);
}

还有我上传图片的电话:

        //Already checked to make sure mImageUri is not null
        File file = new File(StringUtils.getPath(this, mImageUri));
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);

        RetrofitInterfaces.IUploadImages service = RetrofitClientInstance.getRetrofitInstance()
                .create(RetrofitInterfaces.IUploadImages.class);
        //Also checked to make sure mGeneraredUrl is also not null
        Call<String> call = service.listRepos(mGeneratedUrl, requestFile);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if(response.isSuccessful()){
                    Log.d(TAG, "onResponse: Success?");
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d(TAG, "onFailure: Failed: " + t);
            }
        });         

我已将存储桶公开。调用没有失败,但在 onResponse 中我得到的响应代码为 403。

【问题讨论】:

  • 能否添加错误日志(在onFailure() 中添加 t.printstackTrace())?
  • 通话没有失败,但我收到 403 错误

标签: android amazon-web-services amazon-s3 retrofit retrofit2


【解决方案1】:

终于弄明白了..你的预签名 url 函数需要具有与

相同的内容类型

RequestBody.create(MediaType.parse("image/jpeg"), file);

所以在我的参数中

var params = {
    Bucket: 'my-bucket-name',
    Key: 'test-key',
    Expires: signedUrlExpireSeconds,
    ContentType: "image/jpeg"
};

内容类型需要在客户端和功能端相同,否则会出现 403 错误...

【讨论】:

  • 这与为什么params首先需要提供ContentType有关——它是一个标头,其值必须包含在签名算法的输入中,只要它存在于发送到 S3 的请求。
猜你喜欢
  • 2019-03-25
  • 2016-10-12
  • 2020-09-30
  • 2020-09-16
  • 1970-01-01
  • 2017-10-30
  • 2021-02-15
  • 1970-01-01
  • 2021-09-17
相关资源
最近更新 更多