我知道我回答晚了,但这会帮助其他来这里寻找答案的人。
目前,上传多个文件的唯一选择是使用循环将列表中的文件作为单个文件传递,但这是我昨晚发现并实现的。到目前为止我已经测试过很多次了。
这种方法的优点是它对每个文件同时运行,而不是等待每个文件先上传或下载才对下一个文件进行操作。
这就是我发现的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为了这。