I've got a simple file upload system in my app that uploads a .mp3
file to firebase. I would like to check to make sure the file being uploaded is definitely a .mp3
file and is no bigger than 80MB. Is there a way to do this?
Here is my code for uploading the files, at the moment:
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();
}
});
}
});
}
So, basically, you have to use File Metadata . Considering that you are getting the reference right and everything about the upload process is right, here is the way to do what you want:
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 :(
}
});
Now that you have the size (in megabytes) and the content type you can just use a if
statement like this:
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
}
As the OP pointed out it's much better to use the .matches()
function, which, in this instance, is the only one that works.
NOTE: If you planning on deleting the file from firebase storage in case it's bigger than 80MB or it's not an mp3
file, I suggest that you do these things before uploading the files. Basically, check if your file is mp3
and it's smaller than 80MB, then go upload it. It improves the flow of the program and it's, frankly, a better way to do it anyways.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.