繁体   English   中英

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

[英]Uploading an image from gallery to s3 bucket - Creating a file object?

AWS开发工具包需要一个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()));
        }
    }
}

您可以从S3TransferUtilitySample应用程序使用此功能来获取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

您可以这样使用

下面的代码用于访问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();
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM