Upload an image from Android to Amazon S3?

前端 未结 7 2061
不知归路
不知归路 2021-02-01 06:42

I need to upload a bitmap to Amazon S3. I have never used S3, and the docs are proving less than helpful as I can\'t see anything to cover this specific requirement. Unfortunate

7条回答
  •  生来不讨喜
    2021-02-01 07:41

    You can use a library called S3UploadService. First you would need to convert your Bitmap to a File. To do so take a look at this post:

    Convert Bitmap to File

    S3UploadService is a library that handles uploads to Amazon S3. It provides a service called S3UploadService with a static method where you provide a Context (so the static method can start the service), a File, a boolean indicating if said file should be deleted after upload completion and optionally you can set a callback (Not like an ordinary callback though. The way this works is explained in the README file).

    It's an IntentService so the upload will run even if the user kills the app while uploading (because its lifecycle is not attached to the app's lifecycle).

    To use this library you just have to declare the service in your manifest:

    
    
        ...
    
        
    
    

    Then you build an S3BucketData instance and make a call to S3UploadService.upload():

        S3Credentials s3Credentials = new S3Credentials(accessKey, secretKey, sessionToken);
        S3BucketData s3BucketData = new S3BucketData.Builder()
                .setCredentials(s3Credentials)
                .setBucket(bucket)
                .setKey(key)
                .setRegion(region)
                .build();
    
        S3UploadService.upload(getActivity(), s3BucketData, file, null);
    

    To add this library you need to add the JitPack repo to your root build.gradle:

    allprojects {
        repositories {
            ...
            maven { url "https://jitpack.io" }
        }
    }
    

    and then add the dependency:

    dependencies {
        compile 'com.github.OneCodeLabs:S3UploadService:1.0.0@aar'
    }
    

    Here is a link to the repo: https://github.com/OneCodeLabs/S3UploadService

    This answer is a bit late, but I hope it helps someone

提交回复
热议问题