亚马逊S3上传多个文件的Android [英] Amazon s3 upload multiple files android

查看:354
本文介绍了亚马逊S3上传多个文件的Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

万一仍然有人在寻找解决方案,我最终在代码爆炸中使用了循环,而我没有找到可以上传多个文件的官方api.

Incase anyone still looking for a solution i ended up using a loop on the code blew i did not find an official api to do multiple files upload.

-------

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

I have an ArrayList of ImageFiles, that I want to upload to Amazon s3. Their doc provides this code:

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()));

但是此代码仅占用一个文件.如何一次上传多个文件?并且,如果他们不允许这样做,以便用户可以发出更多请求,那么还有什么替代方法?

But this code only takes one file. How can i upload multiple files at once? And if they do not allow this so user can make more requests , what the alternative to do this ??

推荐答案

我知道我来晚了,但是它将帮助其他会来这里寻找答案的人.

I know I'm late to answer but it will help others who'll come here looking for an answer.

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

Currently, the only option to upload multiple files is to use a loop passing the files from list as individual file but here's what I found last night and implemented it. I've tested it many times so far.

此方法的优点是,它对每个文件同时运行,而不必等待每个文件先上传或下载即可对下一个文件进行操作.

Advantage of this method is it runs concurrently for every file and not wait for every file to upload or download first to operate on the next file.

这就是我在此处找到的东西但我已经对其进行了一些修改,以便在Kotlin中使用.

It's what I found here but I've modified it a little bit for my use in 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的函数,如下所示-

  • I've created a function for returning S3Client which is as follows -

    fun s3ClientInitialization(context: Context): AmazonS3 {
        val cognitoCachingCredentialsProvider = CognitoCachingCredentialsProvider(
            context,
            your key,
            region
        )
        return AmazonS3Client(
            cognitoCachingCredentialsProvider,
            Region.getRegion(Regions.YOUR_REGION)
        )
    }
    

  • 然后,将其命名为-

  • Then, Call it as -

     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.

    I've shared the complete working code, you can change it as you need. You can use the above MultiUploaderS3 class in the same class as well which will obviously make things easier to access the TransferListener.

    要进行下载,请更改

    transferUtility.upload(bucketName,toRemoteKey, aLocalFile)

    transferUtility.download(bucketName, fromRemoteKey, aLocalFile)

    并命名为

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

    这将使本地文件路径映射传递给键.

    What this will do is it will pass a map of Local file path to Keys.

    我已经尝试过一次运行一次上传10个文件,并且上传所有文件大约需要4-5秒,不过这也取决于您的互联网连接.我希望下载部分也能正常工作.询问我是否有东西,或为此检查我的 Github .

    I have tried uploading 10 files in a single run many times and it takes around 4-5 seconds to upload all of them, it also depends on your internet connection though. I hope the downloading part will work as well. Ask me if there's something or check my Github for this.

    这篇关于亚马逊S3上传多个文件的Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆