Skip to content

Instantly share code, notes, and snippets.

@jirawatee
Last active April 17, 2019 05:02
Show Gist options
  • Select an option

  • Save jirawatee/bd29dd41a5a815e007bb91b16690b1cd to your computer and use it in GitHub Desktop.

Select an option

Save jirawatee/bd29dd41a5a815e007bb91b16690b1cd to your computer and use it in GitHub Desktop.
Firebase Storage - Upload from local file (Full)
private void uploadFromFile(String path) {
Uri file = Uri.fromFile(new File(path));
StorageReference imageRef = folderRef.child(file.getLastPathSegment());
StorageMetadata metadata = new StorageMetadata.Builder()
.setContentType("image/jpg")
.setCustomMetadata("country", "Thailand"
.build();
UploadTask uploadTask = imageRef.putFile(file, metadata);
Helper.initProgressDialog(this);
Helper.mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mUploadTask.cancel();
}
});
Helper.mProgressDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Pause", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mUploadTask.pause();
}
});
Helper.mProgressDialog.show();
mUploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Helper.dismissProgressDialog();
mTextView.setText(String.format("Failure: %s", exception.getMessage()));
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Helper.dismissProgressDialog();
findViewById(R.id.button_upload_resume).setVisibility(View.GONE);
imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
mTextView.setText(uri.toString());
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress = (int) ((100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
Helper.setProgress(progress);
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
@Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
findViewById(R.id.button_upload_resume).setVisibility(View.VISIBLE);
mTextView.setText(R.string.upload_paused);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment