首页 > 解决方案 > 如何按arraylist中的顺序将多个文件上传到firebase数据库?

问题描述

我正在尝试将多个图像添加到 firebase,但它似乎没有按顺序上传。我相信 myUrlList 的添加取决于上传到服务器的顺序。有什么方法可以将 myUrlsList 与 imageUrlList 排序相同吗?

    for(int i=0; i< imageUriList.size(); i++){
            final StorageReference filereference = storageReference.child(System.currentTimeMillis()
                    + "." + getFileExtension(imageUriList.get(i)));

            uploadTask = filereference.putFile(imageUriList.get(i));
            uploadTask.continueWithTask(new Continuation() {
                @Override
                public Object then(@NonNull Task task) throws Exception {
                    if(!task.isSuccessful()){
                        throw task.getException();
                    }

                    return filereference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if(task.isSuccessful()){

                        Uri downloadUri = task.getResult();
                        myUrl = downloadUri.toString();
                        myUrlList.add(myUrl);

标签: androidfirebasefirebase-realtime-databasefirebase-storage

解决方案


即使您使用循环,理论上,图像的上传也应该按照迭代的顺序,您无法知道实际将每个图像分别上传到 Firebase 存储需要多少时间。正如@DougStevenson 在他的评论中提到的那样,您正在“并行”上传所有内容。因此,即使较小的图像位于较大的图像之后,较小尺寸的图像也可以比较大尺寸的图像上传得更快,因为上传所需的时间更短。

解决这个问题的解决方案是等到一张图片上传完成后,在上一张图片上传完成后开始下一次上传。这通常是通过递归来完成的,使用一个调用自身的方法。

private void uploadImageToFirebaseStorage() {
    if (imageUriList.size() > 0) {
        Uri imageUri = imageUriList.get(0);
        StorageReference filereference = storageReference.child(System.currentTimeMillis()
                + "." + getFileExtension(imageUri));
        imageUriList.remove(0);
        uploadTask = filereference.putFile(imageUri);
        uploadTask.continueWithTask(new Continuation() {
            @Override
            public Object then(@NonNull Task task) throws Exception {
                if(!task.isSuccessful()){
                    throw task.getException();
                }

                return filereference.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    myUrl = downloadUri.toString();
                    myUrlList.add(myUrl);
                    uploadBeerImageToFirebaseStorage(); //Call when completes
                }
            }
        });
    }
}

首先,使用uploadImageToFirebaseStorage(). 上传图像后,该方法将检查是否还有更多工作需要完成,如果是,则重新调用自身。


推荐阅读