How to upload an image to Firebase storage?

前端 未结 5 1308
独厮守ぢ
独厮守ぢ 2021-01-04 07:55

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 fai

相关标签:
5条回答
  • 2021-01-04 08:31

    this method worked for me as if todate:

    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();
            }
        });
    }
    
    0 讨论(0)
  • 2021-01-04 08:35

    Simply call this method to store your image to 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);
           //For the API less than 28 (Android version 8 )
           //String base64Image = android.util.Base64.encodeToString(bytes, android.util.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);
        }
    

    For more details see these examples:

    • Sample 1
    • Sample 2
    0 讨论(0)
  • 2021-01-04 08:42

    Upload multilple images to Firebase storage.

    It is working for me.

    using this library

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

    At the top

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

    onCreate()

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

    button click 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);
    
                }
            });
    

    Activity result

    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 讨论(0)
  • 2021-01-04 08:44

    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;
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-04 08:45

    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'

    0 讨论(0)
提交回复
热议问题