简体   繁体   English

如何将多个图像上传到 FiresbaseStorage 并在 JetpackCompose 中取回 URL

[英]How to Upload Multiple images to FiresbaseStorage and get back the urls in JetpackCompose

I got an idea from Alex Mamo How to upload an image to Firebase how to upload images to Firebase Storage and get back the URL back and upload to Firestore using MVVM and Hilt dependency but how to upload an ArrayList of images URI to Storage and get back the URLs.我从 Alex Mamo 那里得到了一个想法如何将图像上传到 Firebase如何将图像上传到 Firebase 存储并取回 URL 并使用 MVVM 和 Hilt 依赖项上传到 Firestore 但如何将图像 URI 的 ArrayList 上传到存储并取回网址。

I am getting the Selected Images Uri from the gallery in my ViewModel我正在从我的 ViewModel 中的图库中获取 Selected Images Uri

    fun updateSelectedImageList(listOfImages: List<Uri>) {
    val updatedImageList = state.productImagesList.toMutableList()
    viewModelScope.launch {
        updatedImageList += listOfImages
        state = state.copy(
            productImagesList = updatedImageList.distinct()
        )
    }
}

Please correct me if my response is wrong for the list of Uri images如果我对 Uri 图片列表的回答有误,请纠正我

Repository资料库

typealias AddCategoryResponse = Response<Boolean>
typealias AddContentUriResponse = Response<Uri>
typealias AddProductImagesResponse = Response<ProductImages>

suspend fun addProductImagesToFirebaseStorage(productImages: List<Uri>) : AddProductImagesResponse

suspend fun addMainCategoryImageToFirebaseStorage(imageUri: Uri,upcomingCat: Int) : AddContentUriResponse

suspend fun addMainCategoryToFirestore(mainCategory: MainCategory) : AddCategoryResponse

i wanted a create fuction to add multiple images and get back the updated images urls back method我想要一个创建功能来添加多个图像并取回更新的图像 url 返回方法

my Implementation我的实现

@Singleton
class AdminRepositoryImpl @Inject constructor(
@Named("mainCategory")
private val categoryRef: CollectionReference,
@Named("product")
private val productRef: CollectionReference,
@Named("tags")
private val tagsRef: CollectionReference,

private val categoryImageStorage: FirebaseStorage,
) : AdminRepository {

override suspend fun addProductImagesToFirebaseStorage(productImages: List<Uri>): 
AddProductImagesResponse {
    return try {
        val date = System.currentTimeMillis()
        val productDownloadUrls: List<URL> = emptyList()
        productDownloadUrls = //Need to get Success Response of the List Images
  

    categoryImageStorage.reference.child("HomeFeed")
   .child("Products")
            .child("Products$date")

    }
}

override suspend fun addMainCategoryImageToFirebaseStorage(
    imageUri: Uri, upcomingCat: Int,
): AddContentUriResponse {
    return try {
       
            val date = System.currentTimeMillis()
            val downloadUrl =
                categoryImageStorage.reference.child("HomeFeed").child("SubCategory")
                    .child("SubCategoryImage$date")
                    .putFile(imageUri).await()
                    .storage.downloadUrl.await()
            Success(downloadUrl)
        }

    } catch (e: Exception) {
        Failure(e)
    }
}

Getting back the url for uploading a image取回上传图片的url

@Composable
fun AddCategoryImageToStorage(
viewModel: CategoryViewModel = hiltViewModel(),
addCategoryImageToStorage : (downloadUrl: Uri) -> Unit
) {
when(val addCategoryImageToStorageResponse = 
viewModel.addCategoryImageToStorageResponse){
    is Response.Loading -> ProgressBar()
 is Response.Success -> addCategoryImageToStorageResponse.data?.let{ downloadUrl - >
        LaunchedEffect(downloadUrl){
            addCategoryImageToStorage(downloadUrl)
        }
    }
    is Response.Failure -> LaunchedEffect(Unit){
        print(addCategoryImageToStorageResponse.e)
    }
  }

}

UseCases are also used UseCases也被使用

I actually wrote that article, and yes, it only explains how to upload a single file.我实际上写了那篇文章,是的,它只解释了如何上传单个文件。 But the mechanism to upload multiple files is almost the same, except for the fact that you should wait to upload all images.但是上传多个文件的机制几乎是一样的,除了你应该等待上传所有图片。 When you're calling putFile(Uri uri) method on a StorageReference object like below:当您在StorageReference object 上调用putFile(Uri uri)方法时,如下所示:

categoryImageStorage.reference.child("HomeFeed")
                              .child("SubCategory")
                              .child("SubCategoryImage$date")
                              .putFile(imageUri) //👈

The type of object that is returned is UploadTask .返回的 object 的类型是UploadTask This class is a subclass of StorageTask , which in terms is a subclass of ControllableTask , which is also a subclass of CancellableTask , which finally is a subclass of Task .这个 class 是StorageTask的子类,它是ControllableTask的子类,也是CancellableTask的子类,最后是Task的子类。 Because of the inheritance relationship between these classes, you can call await(), each time you upload a file.因为这些类之间是inheritance的关系,每次上传一个文件都可以调用await()。 Since you need to upload multiple files, you need to add all those Task objects that result in a List<UploadTask> .由于您需要上传多个文件,因此您需要添加所有产生List<UploadTask>的 Task 对象。 Once the list is full of objects, pass that list to Tasks#whenAllSuccess(Collection> tasks) method.一旦列表中充满了对象,将该列表传递给Tasks#whenAllSuccess(Collection> tasks)方法。 This method returns an object of type Task<List<TResult>> .此方法返回 object 类型的Task<List<TResult>> That being said, you can call await() to wait for the upload operations to complete.也就是说,您可以调用 await() 来等待上传操作完成。

If the above operation is not fast enough, then please check my answer from the following post:如果上面的操作不够快,请查看我在下面帖子中的回答:

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

相关问题 SwiftUI:上传多张图片到Firebase - SwiftUI: upload multiple images to Firebase 从图库中选择多张图片,然后将它们上传到 Firebase Storgae - 但出现 ENOENT(没有此类文件或目录)错误 - Select multiple images from gallery and then upload them to Firebase Storgae - but get an ENOENT (No such file or directory) error 一次性上传多张图片到Firebase Storage - Upload multiple images to Firebase Storage AT ONCE 如何将图像上传到 AWS Amplify - How to upload images to AWS Amplify 如何使用 reactjs 在 firebase v9 云存储中上传多张图片 - How can I upload multiple images in firebase v9 cloud storage using reactjs 我怎样才能从 html 获取图像的单独 url,如下 http(s)://<hostname> /<chosenpath> /1</chosenpath></hostname> - How can i get seperate urls for images from html as follows http(s)://<hostname>/<chosenpath>/1 我们如何在单个 S3 存储桶中托管多个 HTML 文件以获取每个文件的单独 URL? - How do we host multiple HTML files in a single S3 bucket to get separate URLs for each file? 如何根据来自 firestore 的 url 显示图像列表 - How to display a list of images based off of urls from firestore 如何上传SVG张图片到firebase存储? - How to upload SVG images on firebase storage? 使用 s3 中的节点上传多个图像 map 问题 - Upload multiple images with node in s3 map problem
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM