[英]How to get downloadURL of uploaded file in firebase storage on Java Spring Boot
[英]How to check the filetype of an uploaded file on Cloud Storage for Firebase?
我的應用程序中有一個簡單的文件上傳系統,可以將.mp3
文件上傳到 firebase。 我想檢查以確保上傳的文件絕對是.mp3
文件並且不大於 80MB。 有沒有辦法做到這一點?
這是我目前上傳文件的代碼:
private void getMixForUpload() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("mp3/*");
Intent chooser = Intent.createChooser(intent, "Choose Your Mix");
startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == ACTION_REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
StorageReference filepath = FirebaseStorage.getInstance().getReference().child("DjMixes").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getMetadata().getReference().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
firebaselogourl = downloadUrl.toString();
}
});
}
});
}
所以,基本上,你必須使用File Metadata 。 考慮到您獲得了正確的參考並且有關上傳過程的所有內容都是正確的,這是執行您想要的操作的方法:
taskSnapshot.getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
@Override
public void onSuccess(StorageMetadata storageMetadata) {
long sizeMB = storageMetadata.getSizeBytes() / (1024 * 1024);
String fileType = storageMetadata.getContentType();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle your error, something bad happened :(
}
});
現在您有了大小(以兆字節為單位)和內容類型,您可以使用這樣的if
語句:
if (fileType.matches("audio/mpeg") && sizeMB < 80)) {
//your file is a audio file congratulations
//your file also is bellow 80mb, good :)
} else {
//the above statement is not true
}
正如 OP 指出的那樣,最好使用.matches()
function,在這種情況下,它是唯一有效的。
注意:如果您打算從 firebase 存儲中刪除大於 80MB 或不是mp3
文件的文件,我建議您在上傳文件之前執行這些操作。 基本上,檢查您的文件是否為mp3
且小於 80MB,然后 go 上傳。 它改善了程序的流程,坦率地說,無論如何,它是一種更好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.