web-dev-qa-db-fra.com

Comment télécharger une image sur le stockage Firebase?

J'essaie de télécharger un tableau d'octets simple dans le stockage Firebase, mais mon onFailureListener continue à être appelé et à me reconnecter en disant que le téléchargement a échoué. J'espère que vous pouvez me dire ce qui ne va pas avec mon code.

Au sommet, j'ai

 //Firebase
    private Firebase mRef;
    private StorageReference storageRef;

Puis dans onStart()

@Override
protected void onStart() {
    super.onStart();
    googleApiClient.connect();
    //Firebase
    mRef = new Firebase("link to firebase account");
    FirebaseStorage storage = FirebaseStorage.getInstance();
    storageRef = storage.getReferenceFromUrl("link to storage");

}

Puis dans ma onActivityResult()

      @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            addImageImageView.setVisibility(View.GONE);
            if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK && data != null) {
                //First we gotta make sure to add the images to
                ArrayList<Image> imagesFromGallery = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
                for (int i = 0; i < imagesFromGallery.size(); i++) 
                {
                    try {
                        //try uploading it
                        InputStream stream = new FileInputStream(new File(imagesFromGallery.get(i).path));
                        StorageReference imageStorage = storageRef.child("cardImages/" + "testImages");
                        UploadTask uploadTask = imageStorage.putStream(stream);
                        uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.d("myStorage","failure :(");
                        }
                    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Log.d("myStorage","success!");
                        }
                    });
                    catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    } catch (FileNotFoundException e) {
                     e.printStackTrace();
                }
           }
      }

Voici ma trace de pile:

11-13 21:27:00.392 31388-996/com.daprlabs.aaron.swipedeck2 E/StorageException: StorageException has occurred.
   User does not have permission to access this object.
    Code: -13021 HttpResult: 403
11-13 21:27:00.392 31388-996/com.daprlabs.aaron.swipedeck2 E/StorageException: The server has terminated the upload session
   Java.io.IOException: The server has terminated the upload session
       at com.google.firebase.storage.UploadTask.az(Unknown Source)
       at com.google.firebase.storage.UploadTask.ay(Unknown Source)
       at com.google.firebase.storage.UploadTask.run(Unknown Source)
       at com.google.firebase.storage.StorageTask$5.run(Unknown Source)
       at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1113)
       at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:588)
       at Java.lang.Thread.run(Thread.Java:818)
11-13 21:27:00.406 31388-31388/com.daprlabs.aaron.swipedeck2 D/myStorage: failure :(
10
TheQ

Vous devez soit vous connecter à l'utilisateur, soit modifier les règles de sécurité pour autoriser l'accès public. Ceci est expliqué dans la documentation de Firebase Storage Security .

Pour le développement initial, vous pouvez modifier les règles dans la console Firebase pour autoriser l'accès public:

service firebase.storage {
  match /b/project-XXXXXXXXXXXXXX.appspot.com/o {
    match /{allPaths=**} {
      // Provide access to all users
      allow read: if true;
      allow write: if true;
    }
  }
}
9
Bob Snyder

Je télécharge des images en utilisant ce code:

private void uploadFile(Bitmap bitmap) {
            FirebaseStorage storage = FirebaseStorage.getInstance();
            StorageReference storageRef = storage.getReferenceFromUrl("Your url for storage");
            StorageReference mountainImagesRef = storageRef.child("images/" + chat_id + Utils.getCurrentTimeStamp() + ".jpg");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
            byte[] data = baos.toByteArray();
            UploadTask uploadTask = mountainImagesRef.putBytes(data);
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle unsuccessful uploads
                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();
                    sendMsg("" + downloadUrl, 2);
                    Log.d("downloadUrl-->", "" + downloadUrl);
                }
            });

        }

Dépendance:

Niveau de projet Gradel: classpath 'com.google.gms:google-services:3.0.0'

Niveau d'application: compile 'com.google.firebase:firebase-storage:9.0.2'

5
Dhaval Solanki

Appelez simplement cette méthode pour stocker votre image dans Firebase.

private void storeImageToFirebase() {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 8; // shrink it down otherwise we will use stupid amounts of memory
    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoUri.getPath(), options);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] bytes = baos.toByteArray();
    String base64Image = Base64.encodeToString(bytes, Base64.DEFAULT);

    // we finally have our base64 string version of the image, save it.
    firebase.child("pic").setValue(base64Image);
    System.out.println("Stored image with length: " + bytes.length);
}

Pour plus de détails, consultez ces exemples:

3
Magesh Pandian

cette méthode a fonctionné pour moi comme si à ce jour:

private void uploadImage(Bitmap bitmap) {
    progressDialog.show();
    final StorageReference ref = storageReference.child("drivers/" + UserDto.getId() + ".jpg");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
    byte[] data = baos.toByteArray();

    final UploadTask uploadTask = ref.putBytes(data);
    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            progressDialog.dismiss();
            Toast.makeText(ProfileActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();

            uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }
                    return ref.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downUri = task.getResult();
                        Log.d("Final URL", "onComplete: Url: " + downUri.toString());
                    }
                }
            });
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            progressDialog.dismiss();
            Toast.makeText(ProfileActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}
2
shanezzar

Téléchargez des images multilple vers le stockage Firebase.

Ça marche pour moi.

en utilisant cela bibliothèque

  compile 'com.github.darsh2:MultipleImageSelect:3474549'

Au sommet

private StorageReference storageRef;
private FirebaseApp app;
private FirebaseStorage storage;

onCreate ()

app = FirebaseApp.getInstance();
storage =FirebaseStorage.getInstance(app);

bouton cliquez sur l'action

   Gallary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent intent = new Intent(ChatActivity.this, AlbumSelectActivity.class);
                intent.putExtra(Constants.INTENT_EXTRA_LIMIT, 10);
                startActivityForResult(intent, Constants.REQUEST_CODE);

            }
        });

Résultat de l'activité

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
        ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
        Uri[] uri=new Uri[images.size()];
        for (int i =0 ; i < images.size(); i++) {
            uri[i] = Uri.parse("file://"+images.get(i).path);
            StorageReference ref = storage.getReference("photos").child(uri[i].getLastPathSegment());
            ref.putFile(uri[i])
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Uri downloadUrl = taskSnapshot.getDownloadUrl();
                            String content = downloadUrl.toString();

                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {

                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            //displaying the upload progress
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                        }
                    });

          }
        }

    }
0
Ansal Rabin