Jusqu'à présent, pour obtenir l'URL d'un fichier sur le stockage dans Firebase, j'avais l'habitude de faire cela taskSnapshot.getDownloadUrl
, mais est maintenant obsolète, quelle méthode dois-je utiliser?
Comme Doug dit, vous devrez l'exécuter dans une tâche
Voici un aperçu de la façon dont vous devez l'implémenter
final StorageReference ref = storageRef.child("your_REF");
uploadTask = ref.putFile(file);
Task<Uri> urlTask = 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();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String downloadURL = downloadUri.toString();
} else {
// Handle failures
// ...
}
}
});
Pour plus d'informations sur son implémentation, vous pouvez consulter cette question github ouverte 7 jours après avoir répondu à cette question https://github.com/udacity/and-nd-firebase/issues/41
Ce code fonctionne pour moi.
Tu peux essayer.
package br.com.amptec.firebaseapp;
import Android.graphics.Bitmap;
import Android.net.Uri;
import Android.provider.ContactsContract;
import Android.support.annotation.NonNull;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.util.Log;
import Android.view.View;
import Android.widget.Button;
import Android.widget.ImageView;
import Android.widget.Toast;
import com.google.Android.gms.tasks.OnCompleteListener;
import com.google.Android.gms.tasks.OnFailureListener;
import com.google.Android.gms.tasks.OnSuccessListener;
import com.google.Android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import Java.io.ByteArrayOutputStream;
import Java.util.UUID;
public class MainActivity extends AppCompatActivity {
private DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
private FirebaseAuth auth = FirebaseAuth.getInstance();
private Button btnUpload;
private ImageView imgPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnUpload = findViewById(R.id.btnUpload);
imgPhoto = findViewById(R.id.imgPhoto);
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imgPhoto.setDrawingCacheEnabled(true);
imgPhoto.buildDrawingCache();
Bitmap bitmap = imgPhoto.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String fileName = UUID.randomUUID().toString();
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference images = storageReference.child("images");
StorageReference imageRef = images.child(fileName + ".jpeg");
UploadTask uploadTask = imageRef.putBytes(imageBytes);
uploadTask.addOnFailureListener(MainActivity.this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Error: " +
e.getMessage(), Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(MainActivity.this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//Uri url = taskSnapshot.getDownloadUrl();
Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl();
while(!uri.isComplete());
Uri url = uri.getResult();
Toast.makeText(MainActivity.this, "Upload Success, download URL " +
url.toString(), Toast.LENGTH_LONG).show();
Log.i("FBApp1 URL ", url.toString());
}
});
}
});
}
}
Vous pouvez utiliser StorageReference.getDownloadUrl () . Veuillez noter qu'il renvoie une tâche. Vous devrez donc vous rappeler de la traiter de manière asynchrone comme toute autre tâche.
//Create an instance of StorageReference first (here in this code snippet, it is storageRef)
StorageReference filepath = storageRef.child("images.jpg");
//If file exist in storage this works.
filepath.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
String downloadUrl = task.getResult().toString();
// downloadurl will be the resulted answer
}
});
Ajoutez le code ci-dessous:
Task<Uri> downUrl=taskSnapshot.getMetadata().getReference().getDownloadUrl();
Log.i("url:",downUrl.getResult().toString());
Vous n'obtiendrez pas l'URL de téléchargement de l'image maintenant en utilisant
ImageUrl = taskSnapshot. getDownloadUrl (). ToString (); Cette méthode est obsolète.
Au lieu de cela, vous pouvez utiliser la méthode ci-dessous
uniqueId = UUID.randomUUID().toString();
ur_firebase_reference = storageReference.child("user_photos/" + uniqueId);
Uri file = Uri.fromFile(new File(mphotofile.getAbsolutePath()));
UploadTask uploadTask = ur_firebase_reference.putFile(file);
Task<Uri> urlTask = 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();
}
// Continue with the task to get the download URL
return ur_firebase_reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
System.out.println("Upload " + downloadUri);
Toast.makeText(mActivity, "Successfully uploaded", Toast.LENGTH_SHORT).show();
if (downloadUri != null) {
String photoStringLink = downloadUri.toString(); //YOU WILL GET THE DOWNLOAD URL HERE !!!!
System.out.println("Upload " + photoStringLink);
}
} else {
// Handle failures
// ...
}
}
});
Vous pouvez suivre la progression du téléchargement en ajoutant des écouteurs Progress,
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
System.out.println("Upload is " + progress + "% done");
Toast.makeText(mContext, "Upload is " + progress + "% done", Toast.LENGTH_SHORT).show();
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
@Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).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) {
// Handle successful uploads on complete
// ...
}
});
Utilisez simplement une tâche au lieu de ref.putFile (uriImage) .addOnSuccessListener (new OnSuccessListener () De nos jours, les références de firebase suggèrent l'utilisation d'objets Uploadtask
Je l'ai fait comme ça:
UploadTask uploadTask;
uploadTask = storageReferenceProfilePic.putFile(uriProfileImage );
Task<Uri> urlTask = 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();
}
// Continue with the task to get the download URL
return storageReferenceProfilePic.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
progressBarImageUploading.setVisibility(View.GONE);
Uri downloadUri = task.getResult();
profileImageUrl = downloadUri.toString();
ins.setText(profileImageUrl);
} else {
// Handle failures
// ...
}
}
});
Notez ces lignes dans le code ci-dessus:
Uri downloadUri = task.getResult();
profileImageUrl = downloadUri.toString();
Maintenant, profileImageUrl contient quelque chose comme " http: // addressofimage ", qui correspond à l'URL permettant d'accéder à l'image.
Vous êtes maintenant libre d'utiliser String profileImageUrl comme bon vous semble. Par exemple, chargez l'URL dans un ImageView à l'aide de bibliothèques Glide ou Fresco.