Good day. The problem is that I upload a picture to the firebase server in my android application as follows

/** * Upload image from Bitmap localImage to Firebase server */ public void loadImageToServer(){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); localImg.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] dataBAOS = baos.toByteArray(); /***************** UPLOADS THE PIC TO FIREBASE*****************/ StorageReference storageRef = FirebaseStorage.getInstance(). getReferenceFromUrl("gs://*************.appspot.com/userImages/"); UploadTask uploadTask = storageRef.putBytes(dataBAOS); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { Toast.makeText(rootView.getContext(),R.string.error,Toast.LENGTH_SHORT).show(); showLoading(false); } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { urlToImage = taskSnapshot.getDownloadUrl().toString(); // TODO Здесь отправляется ивент на создание аккаунте в Auth showLoading(false); } }); } 

The file is loaded, but when you try to get the link (apparently), you get an exception like this:

 E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.android.gms.internal.zzbqn: Please sign in before trying to get a token. W/NetworkRequest: no auth token for request 

The userImages folder in firebase exists, the rules are as follows:

 service firebase.storage { match /b/******-******.appspot.com/o { match /{allPaths=**} { allow read, write; } } } 

And besides, the file really appears in the database!

    1 answer 1

    1) It seems you are trying to do an anonymous upload to the server. But you have an irrelevant token. Try calling the logout before the boot method:

     .signOut(); 

    2) If not, you do not need anonymous access to download files (and by default anonymous access is really not needed), then change the rules to these, and try again:

     service firebase.storage { match /b/your_app.appspot.com/o { match /{allPaths=**} { allow read, write: if request.auth != null; } } } 

    Update: In order to send a picture of a user when registering a user, you need to get an ID and continue to work with this ID. This is all done consistently. As soon as the answer is returned that the user is registered - send a picture by this user ID:

     AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); firebaseAuth.signInWithCredential(credential) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (taskResult.isSuccessful()) { //вызываем метод загрузки файла. Например, uploadImage(); } else { Log.e(TAG, "signInWithCredential error: ", taskResult.getException()); } } }); 

    After a successful upload to the user’s folder, you will receive a URL:

     private void uploadImage() { //Prepare file String fileName = ... ; //ваш метод получения имени файла File file = ... ; //ваш метод получения файла //prepare user FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); String userUid = user.getUid(); //prepare storage StorageReference storage = FirebaseStorage.getInstance() .getReferenceFromUrl(BuildConfig.StorageReference); StorageReference fileRef = storage.child(userUid).child(fileName); //upload UploadTask uploadTask = fileRef.putFile(Uri.fromFile(file)); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { //ошибка загрузки } }); uploadTask.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 urlFile = taskSnapshot.getDownloadUrl(); } }); } 
    • When registering, I need to upload the user's picture from the smartphone to the server. And thanks for the answer! - timuruktus
    • Please) Do you want to do this simultaneously with the registration? - Andrew Grow
    • That's right - timuruktus
    • one
      updated the answer - added an example of file upload during registration - Andrew Grow
    • Can I have more details about the ID, please?) How do we get it if the user is not yet registered? Will this ID be reset when you restart the application? Or how? Thank you - timuruktus