![](/img/trans.png)
[英]How to get the download url after uploading a file to firebase storage in springboot
[英]How to get file URL after uploading them to Firebase?
將文件上傳到 Firebase 后,如何獲取它的 URL 以便存儲它供以后使用? 我想將 URL 寫入 Firebase 數據庫,以便其他用戶可以訪問圖像。
我正在像這樣上傳文件:
public void uploadFile()
{
StorageReference filepath = mstorageRef.child("folder").child(filename);
Uri File= Uri.fromFile(new File(mFileName));
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
}
});
}
我已經確認文件實際上正在上傳,所以現在我只需要可以寫入數據庫的 URL。 但是,當我嘗試這樣做時:
Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
它給了我一個錯誤,並說This method should only be accessed from tests or within private scope
我不確定這意味着什么,我也不知道為什么我會收到這個錯誤,因為我正在關注 Firebase 提供的 這個示例。
有沒有新的獲取 URL 的方法?
此外,該 URL 是否特別適用於該項目? 意思是如果我將它存儲到數據庫中並稍后嘗試訪問它,我可以這樣做嗎?
您正在使用已棄用的UploadTask.getDownloadUrl()
。 您可以使用StorageReference.getDownloadUrl() 。
在你的情況下你可以試試這個-
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
//Do what you want with the url
}
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
}
});
注意StorageReference.getDownloadUrl()
返回任務,它必須異步處理,你不能這樣做Uri downloadUrl = photoRef.getDownloadUrl().getResult();
否則你會得到java.lang.IllegalStateException: Task is not yet complete
這種方法也有效,而且稍微簡單一些。
這不是什么“令人難以置信”的東西,但它將您的代碼減少到幾行。 希望這是一個有用的答案。
StorageReference filepath = mstorageRef.child("folder").child(filename);
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot){
Uri downloadUrl = filepath.getDownloadUrl(); // here is Url for photo
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
}
});
如上所述, StorageReference.getDownloadUrl()
返回 Task。
這是我的代碼:
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
String download_url = uri.toString();
mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()) {
mProgressDialog.dismiss();
Toast.makeText(SettingActivity.this, "Successfully uploaded", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(SettingActivity.this, "Error happened during the upload process", Toast.LENGTH_LONG).show();
}
}
});
}
});
}else{
Toast.makeText(SettingActivity.this, "Error happened during the upload process", Toast.LENGTH_LONG ).show();
}
}
});
這里很熱,我做到了
1)這是我的上傳並獲取http url代碼:
UploadTask uploadTask = FirebaseStorage.getInstance().getReference().child("id").child("filename")
.putFile(uri);
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 FirebaseStorage.getInstance().getReference().child(user.getUid()).child(avatarName).getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
FirebaseDatabase.getInstance().getReference().child(user.getUid())
.child(avatarName)
.child("avatar_image")
.setValue(downloadUri.toString());
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
} else {
// Handle failures
// ...
Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show();
}
}
});
2)這是我從圖庫中拾取圖像后的 onActivityResult 代碼
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
// Log.d(TAG, String.valueOf(bitmap));
ivAvatarPic.setImageBitmap(bitmap);
//ImageView imageView = (ImageView) findViewById(R.id.imageView);
//imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用以下代碼
val imageGalleryRef = storageReference?.child(name + "_gallery")
val uploadTask = imageGalleryRef.putFile(file)
uploadTask.addOnFailureListener({ e ->
Log.e(TAG, "onFailure sendFileFirebase " + e.message)
}).addOnCompleteListener(
object : OnCompleteListener<UploadTask.TaskSnapshot> {
override fun onComplete(p0: Task<UploadTask.TaskSnapshot>) {
imageGalleryRef.downloadUrl.addOnSuccessListener { e ->
run {
downloadUrl = e.toString() // e is image download Uri
}
}
}
}
)
試試這個:
filepath.putFile(File).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
String fileUri = task.getResult().getUploadSessionUri().toString();
// Do whatever you want with fileUri
}
}
}) ;
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String category = spinner.getSelectedItem().toString();
String title = ((EditText) findViewById(R.id.post_title)).getText().toString();
String description = ((EditText) findViewById(R.id.post_description)).getText().toString();
final Post post = new Post(userId, category, title, description, latitude, longitude, true);
post.setAddressList(addressLine);
post.setContact(contact);
if (addressLine != null) {
post.setPlace(addressLine.split(",")[2]);
}
post.setId(key);
post.setImage(uri.toString());
databaseReference.setValue(post).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
((EditText) findViewById(R.id.post_title)).setText("");
((EditText) findViewById(R.id.post_description)).setText("");
postImageButton.setImageURI(null);
progressBarDialog.dismiss();
Toast.makeText(PostActivity.this, "Your request is sucessfully completed", Toast.LENGTH_SHORT).show();
} else if (!task.isSuccessful()) {
progressBarDialog.dismiss();
Toast.makeText(PostActivity.this, "Your request is not completed", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
將URI更改為URL
val urlTask = uploadTask.continueWith { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
spcaeRef.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
//URL
val url = downloadUri!!.result
} else {
//handle failure here
}
}
在 Ionic 5 + 電容器中,這就是我最終能夠監控上傳並獲取完成的文件名的方式。
該代碼是從谷歌自己的文檔+一些谷歌搜索中收集的( https://ionicthemes.com/tutorials/about/ionic-firebase-image-upload等等)。
它使用畫布(據我所知)從圖像生成 base64 字符串。 這行得通,而 ionic 的 File 和 Base64 則行不通。
在頁面上,我有一個 <ion-progressbar> 顯示百分比 (this.downloadProgress) 如果它 > 0。我還有一個帶有 src=this.imageUrl 的 <ion-img> 在上傳時顯示圖片。
我無法使上述答案中的任何技術起作用,甚至無法編譯。 但我不知道為什么。
另一個警告是一些示例代碼使用 function() 而不是箭頭語法
encodeImageUri(imageURI, 函數(image64) {
這需要重寫箭頭語法以將“this”綁定/傳遞給調用的函數,如下所示:
encodeImageUri(imageURI, image64 => {
uploadImage(imageURI) {
console.log(`try upload ${imageURI}`)
let storageRef = firebase.storage().ref();
let imageRef = storageRef.child('image').child('imageName');
this.encodeImageUri(imageURI, image64 => {
// create upload task
const uplTask = imageRef.putString(image64, 'data_url');
uplTask.on('state_changed',
snapshot => {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes);
console.log('Upload is ' + progress * 100 + '% done'); // might display this somewhere
this.downloadProgress = progress; // update progress bar
},
error => {
console.log('upload error');
},
() => {
uplTask.snapshot.ref.getDownloadURL()
.then(downloadURL => {
console.log('File available at', downloadURL);
this.imageUrl = downloadURL;
this.downloadProgress = -1; // negative values hide the progress bar
});
}
);
});
}
encodeImageUri(imageUri, callback) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function () {
var aux:any = this;
c.width = aux.width;
c.height = aux.height;
ctx.drawImage(img, 0, 0);
var dataURL = c.toDataURL("image/jpeg");
callback(dataURL);
};
img.src = imageUri;
};
當然,這有點無聊,因為它總是覆蓋相同的 Firebase 存儲文件:) 但這是可以解決的。
不確定這是否是您正在尋找的,因為我正在使用 Kotlin。 這就是我當前項目中對我有用的東西。 我希望它能在將來幫助其他人。
首先,我從相機或畫廊獲取圖像。 我正在使用當前時間戳來使文件名唯一。
fun uploadFileFromMemory() {
showLoading()
val currentTimestamp = System.currentTimeMillis()
val storage = Firebase.storage("Your storage url")
// Create a storage reference from our app
val storageRef = storage.reference
// Create a reference to "mountains.jpg"
val mountainsRef = storageRef.child("images/picture$currentTimestamp.jpg")
// Get the data from an adminImageView as bytes
adminImageView.isDrawingCacheEnabled = true
adminImageView.buildDrawingCache()
val bitmap = (adminImageView.drawable as BitmapDrawable).bitmap
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val data = baos.toByteArray()
var uploadTask = mountainsRef.putBytes(data)
val urlTask = uploadTask.continueWithTask { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
mountainsRef.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
updateServicePicture(downloadUri.toString())
} else {
hideLoading()
showToast("Something went wrong")
}
}
之后,我將獲取新更新文件的 URL,以使用此函數更新我的 firestore 數據庫中的圖片 URL 屬性。
fun updateServicePicture(url: String) {
val db = FirebaseFirestore.getInstance()
val id = arguments?.getString("id")
if (id !== null) {
val ref = db.collection("services").document(id)
// Set the "isCapital" field of the city 'DC'
ref
.update("picture", url)
.addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!")
hideLoading()
showToast("Picture has been successfully updated")
}
.addOnFailureListener { e -> Log.w(TAG, "Error updating document", e)
hideLoading()
showToast("Something went wrong")
}
}
}
hideLoading()、showloading() 和 showToast() 是我用於進度條和 toast 的函數。 我希望這可以幫助某人。 通過文檔和一些測試,我最終讓它工作了。 祝大家編碼愉快。
Future<List<String>> uploadImages(List<String> filepaths) async {
List<String> uploadUrls = [];
await Future.wait(filepaths.map((String filepath) async {
FirebaseStorage storage = FirebaseStorage(storageBucket: 'gs://your-bucket-name.appspot.com');
StorageUploadTask uploadTask = storage.ref().child("images/${basename(filepath)}").putFile(File(filepath));
StorageTaskSnapshot storageTaskSnapshot;
StorageTaskSnapshot snapshot = await uploadTask.onComplete;
if (snapshot.error == null) {
storageTaskSnapshot = snapshot;
final String downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();
uploadUrls.add(downloadUrl);
print('Upload success');
} else {
print('Error from image repo ${snapshot.error.toString()}');
throw ('This file is not an image');
}
}), eagerError: true, cleanUp: (_) {
print('eager cleaned up');
});
return uploadUrls;
}
}
你試過taskSnapshot.getDownloadUrl()
了嗎? 如果這也不起作用,您可以通過mstorageRef.child("folder").child(filename).toString()
在成功偵聽器中獲取圖像位置
試試這個:
final Uri uri = data.getData();
StorageReference filepath = mStorageRef.child("folder").child(filename);
filepath.putFile(uri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
//Getting url where image is stored
//downloadUri will store image URI
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.