亚马逊s3上传多个文件android

2024-03-15

如果有人仍在寻找解决方案,我最终会在代码上使用循环,但我没有找到官方 api 来执行多个文件上传。

-------

我有一个 ImageFiles 的 ArrayList,我想将其上传到 Amazon s3。他们的文档提供了以下代码:

credentials = new BasicAWSCredentials(key, secret);
s3 = new AmazonS3Client(credentials);               
transferUtility = new TransferUtility(s3, getContext());
observer.setTransferListener(new TransferListener() {
    @Override
    public void onStateChanged(int id, TransferState state) {

    }

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

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

    }
});
observer = transferUtility.upload("buket name", upload_file.getNew_name(),
                                   new File(upload_file.getFile_path()));

但这段代码只需要一个文件。如何一次上传多个文件?如果他们不允许这样做,以便用户可以提出更多请求,那么有什么替代方法可以做到这一点?


我知道我回答晚了,但这会帮助其他来这里寻找答案的人。

目前,上传多个文件的唯一选择是使用循环将列表中的文件作为单个文件传递,但这是我昨晚发现并实现的。到目前为止我已经测试过很多次了。

这种方法的优点是它对每个文件同时运行,而不是等待每个文件先上传或下载才对下一个文件进行操作。

这就是我发现的here https://github.com/aws-amplify/aws-sdk-android/issues/505#issuecomment-612187402但为了在 Kotlin 中使用,我对其进行了一些修改。

  • 首先,创建一个类,我给它命名了MultiUploaderS3 -

     import android.content.Context
     import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener
     import com.amazonaws.mobileconnectors.s3.transferutility.TransferState
     import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility
     import io.reactivex.Completable
     import io.reactivex.Observable
     import io.reactivex.Single
     import java.io.File
    
     class MultiUploaderS3 {
    
         private fun transferUtility(context: Context): Single<TransferUtility?>? {
             return Single.create { emitter ->
                 emitter.onSuccess(
                 TransferUtility(s3ClientInitialization(context), context)
                 )
             }
         }
    
         fun uploadMultiple(fileToKeyUploads: Map<File, String>, context: Context): Completable? {
             return transferUtility(context)!!
                 .flatMapCompletable { transferUtility ->
                     Observable.fromIterable(fileToKeyUploads.entries)
                         .flatMapCompletable { entry ->
                             uploadSingle(
                                 transferUtility,
                                 entry.key,
                                 entry.value
                             )
                         }
                 }
         }
    
             private fun uploadSingle(
             transferUtility: TransferUtility,
             aLocalFile: File?,
             toRemoteKey: String?
         ): Completable? {
             return Completable.create { emitter ->
                 transferUtility.upload(bucketName,toRemoteKey, aLocalFile)
                     .setTransferListener(object : TransferListener {
                         override fun onStateChanged(
                             id: Int,
                             state: TransferState
                         ) {
                             if (TransferState.FAILED == state) {
                                 emitter.onError(Exception("Transfer state was FAILED."))
                             } else if (TransferState.COMPLETED == state) {
                                 emitter.onComplete()
                             }
                         }
    
                         override fun onProgressChanged(
                             id: Int,
                             bytesCurrent: Long,
                             bytesTotal: Long
                         ) {
                         }
    
                         override fun onError(id: Int, exception: Exception) {
                             emitter.onError(exception)
                         }
                     })
             }
         }
    
     }
    
  • 我创建了一个返回 S3Client 的函数,如下 -

    fun s3ClientInitialization(context: Context): AmazonS3 {
        val cognitoCachingCredentialsProvider = CognitoCachingCredentialsProvider(
            context,
            your key,
            region
        )
        return AmazonS3Client(
            cognitoCachingCredentialsProvider,
            Region.getRegion(Regions.YOUR_REGION)
        )
    }
    
  • 然后,将其称为 -

     val map: Map<File, String> = yourArrayList.map {it to Your_Key_For_Each_File}.toMap()
     MultiUploaderS3().uploadMultiple(map, this)
         .subscribeOn(Schedulers.io())
         .observeOn(Schedulers.io())
         .subscribe {
             runOnUiThread {
                 Toast(this@AddActivity, "Uploading completed", Toast.LENGTH_LONG).show()
             }
          }
    

我已经分享了完整的工作代码,您可以根据需要进行更改。您可以使用上面的MultiUploaderS3类也在同一个类中,这显然会使访问更容易TransferListener.

对于下载,更改

transferUtility.upload(bucketName,toRemoteKey, aLocalFile) in uploadSingle()

to

transferUtility.download(bucketName, fromRemoteKey, aLocalFile)

并将其称为

val map: Map<File, String> = yourKeysArrayList.map {Your_FILE_For_Each_KEY to it}.toMap()

其作用是将本地文件路径的映射传递给 Keys。

我多次尝试在一次运行中上传 10 个文件,上传所有文件大约需要 4-5 秒,但这也取决于您的互联网连接。我希望下载部分也能正常工作。问我是否有什么事情或者检查我的Github https://github.com/Fauzdar1/MultiUploaderS3为了这。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

亚马逊s3上传多个文件android 的相关文章

随机推荐