Android 将图像从gallery上传到s3 bucket-创建文件对象?

Android 将图像从gallery上传到s3 bucket-创建文件对象?,android,amazon-web-services,amazon-s3,Android,Amazon Web Services,Amazon S3,AWS SDK需要一个文件对象来将数据上传到bucket。创建transferUtility.upload所需的文件对象时遇到问题。我知道新文件(selectedImageUri.getPath())不起作用。我曾经阅读过关于如何从uri生成文件的文章,但似乎没有一种简单的方法可以做到这一点。我是否应该使用除TransferUtility以外的其他工具 public class SettingsActivity extends AppCompatActivity { ... p

AWS SDK需要一个
文件
对象来将数据上传到bucket。创建
transferUtility.upload所需的文件对象时遇到问题。我知道
新文件(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()));
        }
    }
}
公共类设置活动扩展了AppCompatingActivity{
...
私有类更改设置STASK扩展异步任务{
公共无效上载数据(文件映像){
转移效用转移效用=
TransferUtility.builder()
.defaultBucket(“某个桶”)
.context(getApplicationContext())
.s3Client(新的AmazonS3Client(新的BasicAWSCredentials(“某物”)))
.build();
TransferObserver上载Observer=
上传(“somefile.jpg”,图片);
...
}
@凌驾
ActivityResult上的受保护无效(int-reqCode、int-resultCode、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(resultCode==RESULT\u OK){
Uri selectedImageUri=data.getData();
上传数据(新文件(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;
    }
现在,当您拥有文件路径时,您可以从中构造文件对象

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

有关更多信息,您可以试用示例:

您可以这样使用它

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

BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey,secret);
AmazonS3Client s3 = new AmazonS3Client(credentials);
s3.setRegion(Region.getRegion(Regions.US_EAST_1));
Transfer utility是可以将文件上载到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();
            }
        });

“我试过阅读如何从uri生成文件,但似乎没有一种简单的方法”——在
上下文上调用
getContentResolver()
以获取
ContentResolver
。调用
openInputStream()
ContentResolver
上,传递
Uri
,以获取
InputStream
。在您控制的某个文件上打开
FileOutputStream
。将
InputStream
中的字节复制到
OutputStream
。完成。或者,抓取并使用
DocumentFileCompat
copyTo()
为您进行复制。@Commonware因此,如果我理解这是做什么的,它是复制照片的内容以上载到另一个文件,然后使用它,对吗?它是将内容复制到一个文件中。它是否是“另一个文件”这取决于它最初是否是一个文件。非常感谢,我已经面临这个问题好几天了,这个问题是通过这个getPath()方法解决的。