将图像从库上传到s3存储桶 - 创建文件对象?

时间:2018-02-11 09:57:33

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

AWS SDK需要File对象才能将数据上传到存储桶。我在创建transferUtility.upload所需的File对象时遇到问题。我知道new File(selectedImageUri.getPath())不起作用。我已经尝试过阅读如何从uri创建文件,但似乎没有一种简单的方法可以做到这一点。我应该使用TransferUtility以外的其他内容吗?

public class SettingsActivity extends AppCompatActivity {
    ...

    private class ChangeSettingsTask extends AsyncTask<Void, Void, Boolean> {

    public void uploadData(File image) {
        TransferUtility transferUtility =
                TransferUtility.builder()
                        .defaultBucket("some-bucket")
                        .context(getApplicationContext())
                        .s3Client(new AmazonS3Client( new BasicAWSCredentials( "something", "something") ))
                        .build();

        TransferObserver uploadObserver =
                transferUtility.upload("somefile.jpg", image);

        ...
    }

    @Override
    protected void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();
            uploadData(new File(selectedImageUri.getPath()));
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用S3TransferUtilitySample App中的此功能获取URI的文件路径。

    private String getPath(Uri uri) throws URISyntaxException {
        final boolean needToCheckUri = Build.VERSION.SDK_INT >= 19;
        String selection = null;
        String[] selectionArgs = null;
        // Uri is different in versions after KITKAT (Android 4.4), we need to
        // deal with different Uris.
        if (needToCheckUri && DocumentsContract.isDocumentUri(getApplicationContext(), uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                uri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("image".equals(type)) {
                    uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[] {
                        split[1]
                };
            }
        }
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                    MediaStore.Images.Media.DATA
            };
            Cursor cursor = null;
            try {
                cursor = getContentResolver()
                        .query(uri, projection, selection, selectionArgs, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

现在,当你拥有filePath时,可以从中构造文件对象。

File file = new File(filePath);
TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, file.getName(),
file);

有关详细信息,您可以试用样本:https://github.com/awslabs/aws-sdk-android-samples/tree/master/S3TransferUtilitySample

答案 1 :(得分:0)

您可以像这样使用它

下面的代码用于访问您的aws s3,您必须在其中传递accessKey和secretKey作为您的凭据。

BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey,secret);
AmazonS3Client s3 = new AmazonS3Client(credentials);
s3.setRegion(Region.getRegion(Regions.US_EAST_1));

传输实用程序是您可以将文件上传到s3的类。

TransferUtility transferUtility = new TransferUtility(s3, UploadFileActivity.this);

从存储中获取文件的路径,并将其作为文件传递,如下所示

        //You have to pass your file path here.
        File file = new File(filePath);
        if(!file.exists()) {
            Toast.makeText(UploadFileActivity.this, "File Not Found!", Toast.LENGTH_SHORT).show();
            return;
        }
        TransferObserver observer = transferUtility.upload(
                Config.BUCKETNAME,
                "video_test.jpg",
                file
        );

您可以使用observer.setTransferListener来了解上传文件的进度

observer.setTransferListener(new TransferListener() {
            @Override
            public void onStateChanged(int id, TransferState state) {

                if (state.COMPLETED.equals(observer.getState())) {

                    Toast.makeText(UploadFilesActivity.this, "File Upload Complete", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

            }

            @Override
            public void onError(int id, Exception ex) {

                Toast.makeText(UploadFilesActivity.this, "" + ex.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });