Upload a file to AWS S3 pre-signed URL using Retrofit2

前端 未结 2 793
情歌与酒
情歌与酒 2020-12-21 02:06

I\'m trying to upload a file to Amazon\'s S3 using a pre-signed URL. I get the URL from a server which generates the URL & sends it to me as part of a JSON object. I g

相关标签:
2条回答
  • 2020-12-21 02:27

    Use the following while uploading directly to S3 using presigned URL.

    @Multipart
    @PUT
    @Headers("x-amz-acl:public-read")
    Call<Void> uploadFile(@Url String url, @Header("Content-Type") String contentType, @Part MultipartBody.Part part);
    
    0 讨论(0)
  • 2020-12-21 02:37

    With help from a colleague, this is the solution.

    public interface UpdateImageInterface {
        @PUT
        Call<Void> updateImage(@Url String url, @Body RequestBody image);
    }
    

    Calling code:

        String CONTENT_IMAGE = "image/jpeg";
    
        File file = new File(localPhotoPath);    // create new file on device
        RequestBody requestFile = RequestBody.create(MediaType.parse(CONTENT_IMAGE), file);
    
        /* since the pre-signed URL from S3 contains a host, this dummy URL will
         * be replaced completely by the pre-signed URL.  (I'm using baseURl(String) here
         * but see baseUrl(okhttp3.HttpUrl) in Javadoc for how base URLs are handled
         */
        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://www.dummy.com/")
            .build();
    
        UpdateImageInterface imageInterface = retrofit.create(UpdateImageInterface.class);
        // imageUrl is the String as received from AWS S3
        Call<Void> call = imageInterface.updateImage(imageUrl, requestFile);
    

    Javadoc for info on @Url (class Url) & baseUrl() (class Retrofit.Builder)

    MediaType is a class in the OkHttp library that is often used with Retrofit (both from Square). Info about constants passed to the parse method can be found in the Javadoc.

    0 讨论(0)
提交回复
热议问题