Upload an image from Android to Amazon S3?

前端 未结 7 2051
不知归路
不知归路 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:31

    String      ACCESS_KEY="****************",
                SECRET_KEY="****************",
                MY_BUCKET="bucket_name",
                OBJECT_KEY="unique_id";              
      AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
                    AmazonS3 s3 = new AmazonS3Client(credentials);
                    java.security.Security.setProperty("networkaddress.cache.ttl" , "60");
                    s3.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));
                    s3.setEndpoint("https://s3-ap-southeast-1.amazonaws.com/");
                    List buckets=s3.listBuckets();
                    for(Bucket bucket:buckets){
                        Log.e("Bucket ","Name "+bucket.getName()+" Owner "+bucket.getOwner()+ " Date " + bucket.getCreationDate());
                    }
                    Log.e("Size ", "" + s3.listBuckets().size());
                    TransferUtility transferUtility = new TransferUtility(s3, getApplicationContext());
                    UPLOADING_IMAGE=new File(Environment.getExternalStorageDirectory().getPath()+"/Screenshot.png");
                    TransferObserver observer = transferUtility.upload(MY_BUCKET,OBJECT_KEY,UPLOADING_IMAGE);
                    observer.setTransferListener(new TransferListener() {
                        @Override
                        public void onStateChanged(int id, TransferState state) {
                            // do something
                            progress.hide();
                            path.setText("ID "+id+"\nState "+state.name()+"\nImage ID "+OBJECT_KEY);
    
                        }
    
                        @Override
                        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                            int percentage = (int) (bytesCurrent / bytesTotal * 100);
                            progress.setProgress(percentage);
                            //Display percentage transfered to user
                        }
    
                        @Override
                        public void onError(int id, Exception ex) {
                            // do something
                            Log.e("Error  ",""+ex );
                        }
    
                    });
    

提交回复
热议问题