答案 0 :(得分:11)
正如道格所说,你需要在任务
中运行它以下是您需要如何实施它的提示
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
// ...
}
}
});
有关如何实现它的更多信息,您可以查看我在回答https://github.com/udacity/and-nd-firebase/issues/41
后7天打开的这个github问题答案 1 :(得分:3)
此代码对我有用。
您可以尝试。
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());
}
});
}
});
}
}
答案 2 :(得分:2)
您可以使用StorageReference.getDownloadUrl()。请注意,它会返回一个任务,因此您必须记住像执行任何其他任务一样异步处理它。
答案 3 :(得分:1)
//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
}
});
答案 4 :(得分:0)
添加以下代码:
Task<Uri> downUrl=taskSnapshot.getMetadata().getReference().getDownloadUrl();
Log.i("url:",downUrl.getResult().toString());
答案 5 :(得分:0)
您现在将无法使用获取图像的下载网址
ImageUrl = taskSnapshot。 getDownloadUrl ()。toString(); 不建议使用此方法。
您可以使用以下方法
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
// ...
}
}
});
您可以通过添加进度监听器来跟踪上传进度,
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
// ...
}
});
答案 6 :(得分:0)
只需使用Task而不是ref.putFile(uriImage) .addOnSuccessListener(新的OnSuccessListener() 如今,firebase参考建议使用Uploadtask对象
我这样做是这样的:
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
// ...
}
}
});
在上面的代码中注意以下几行:
Uri downloadUri = task.getResult();
profileImageUrl = downloadUri.toString();
现在profileImageUrl包含类似“ http://adressofimage”的内容,这是访问图像的网址
现在,您可以随意使用String profileImageUrl。例如,使用Glide或Fresco库将网址加载到ImageView中。
答案 7 :(得分:0)
将此实现用于您的uploadTask,它将起作用。 :)
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl();
firebaseUri.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String url = uri.toString();
Log.e("TAG:", "the url is: " + url);
String ref = yourStorageReference.getName();
Log.e("TAG:", "the ref is: " + ref);
}
});
}
});
答案 8 :(得分:0)
Task<Uri> task = taskSnapshot.getMetadata().getReference().getDownloadUrl();
task.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String photoLink = uri.toString();
}
});
答案 9 :(得分:0)
使用taskSnapshot.getTask()代替taskSnapshot.getDownloadUrl()对我来说很好。