使用Firebase上传异步多张照片

时间:2016-11-15 23:01:21

标签: android firebase image-uploading firebase-storage

任何人都可以帮助我。

使用Firebase上传多张照片时遇到问题。我的问题是当我循环浏览要上传的照片时,UploadTask似乎在一个单独的线程上工作,所以循环遍历所有照片,而第一张照片仍然上传 我想逐个上传它们,所以除非第一张照片已上传,否则循环不会迭代到下一张照片

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch(item.getItemId()){
        case R.id.add_photo_option:
            item.setEnabled(false);
            final ProgressDialog dialog = new ProgressDialog(getActivity());
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            for (int x = 0; x < photosList.getAdapter().getItemCount(); x++){
                int photoNumber = x+1;
                dialog.setTitle("Uploading photo no: " + photoNumber);
                dialog.show();
                ImageAdapter adapter = (ImageAdapter) photosList.getAdapter();
                Uri photoUri = adapter.getPhotoUri(x);
                String path = "photos/" + UUID.randomUUID() + ".png";
                StorageReference storage = mStorageRef.getReference(path);
                UploadTask task = storage.putFile(photoUri);
                task.addOnProgressListener(getActivity(), new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        long progress = taskSnapshot.getBytesTransferred();
                        long totalBytes = taskSnapshot.getTotalByteCount();
                        dialog.setMessage("Uploading: " + progress + " KBs out of " + totalBytes + " KBs");
                    }
                });
                task.addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        dialog.setMessage("Uploaded");
                        item.setEnabled(true);
                        Toast.makeText(getActivity(), taskSnapshot.getDownloadUrl().toString(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
            dialog.dismiss();
            return true;
        default:
        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:1)

我可以给你一个算法(刚刚回答了JS):

// set it up
firebase.storage().ref().constructor.prototype.putFiles = function(files) { 
  var ref = this;
  return Promise.all(files.map(function(file) {
    return ref.child(file.name).putFile(file);
  }));
}

// use it!
firebase.storage().ref().putFiles(files).then(function(metadatas) {
  // Get an array of file metadata
}).catch(function(error) {
  // If any task fails, handle this
});

您可以使用Android Tasks.whenAlldocsblog post)执行类似操作:创建一系列任务,然后使用whenAll()启动它们