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

前端 未结 2 801
情歌与酒
情歌与酒 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:37

    With help from a colleague, this is the solution.

    public interface UpdateImageInterface {
        @PUT
        Call 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 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.

提交回复
热议问题