Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload an image to Firebase storage?

I'm trying to upload a simple byte array into Firebase storage, but my onFailureListener keeps getting called and logging back to me saying that the upload failed. I'm hoping you guys can tell me whats wrong with my code.

At the top I got

 //Firebase
    private Firebase mRef;
    private StorageReference storageRef;

Then in 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");

}

Then in my 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();
                }
           }
      }

Here is my stack trace:

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 :(
like image 712
TheQ Avatar asked Nov 14 '16 04:11

TheQ


People also ask

Is it possible to store images in Firebase?

The Firebase SDKs for Cloud Storage add Google security to file uploads and downloads for your Firebase apps, regardless of network quality. You can use our SDKs to store images, audio, video, or other user-generated content. On the server, you can use Google Cloud Storage APIs to access the same files.

How can upload image in Firebase storage and get URL?

Image URL is obtained by uploading an image to firebase bucket and then that can return back a URL that URL is a permanent URL which can be open anywhere. Then a user can use this URL for any purpose in its application.


2 Answers

You either need to sign-in the user or change the security rules to allow public access. This is explained in the documentation for Firebase Storage Security.

For initial development, you can change the rules at the Firebase Console to allow public access:

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;
    }
  }
}
like image 135
Bob Snyder Avatar answered Sep 20 '22 12:09

Bob Snyder


I upload images using this 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);
                }
            });

        }

Dependency :

Project Level Gradel : classpath 'com.google.gms:google-services:3.0.0'

App Level Gradel : compile 'com.google.firebase:firebase-storage:9.0.2'

like image 26
Dhaval Solanki Avatar answered Sep 21 '22 12:09

Dhaval Solanki