Please, tell me how to upload image to Firebase
captured on first activity. After send image button pressed image goes to second activity. There I can set in ImageView
but can't upload it in Firebase
storage. Please, tell where I'm wrong.
//camera
camera=(ImageView)findViewById(R.id.cam);
camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_REQUEST_CODE);
// Intent intent = new Intent(Home.this,PostActivity.class);
// startActivity(intent);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==CAMERA_REQUEST_CODE)
{
Uri uri=data.getData();
Intent intent=new Intent(Home.this,PostActivity.class);
intent.putExtra("imgUrl",uri.toString() );
startActivity(intent);
}
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
// path = (Uri) bundle.get("imgUrl");
path = Uri.parse(bundle.getString("imgUrl"));
Log.e("ashish", path + "");
}
ImageView selfiiii = (ImageView) findViewById(R.id.mySelfie);
selfiiii.setImageURI(path);
btnPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startPosting();
}
});
}
public void startPosting() {
dialog.setMessage("posting....");
dialog.show();
final String status = WriteSomthng.getText().toString().trim();
if (!TextUtils.isEmpty(status) && path!=null) {
StorageReference filpath = reference.child("Posts").child(path.getLastPathSegment());
Log.e("irfan sam",filpath+"");
filpath.putFile(path).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference userPost = database.push();
userPost.child("status").setValue(status);
userPost.child("image").setValue(downloadUrl.toString());
userPost.child("userName").setValue(Common.currentUser.getUserName());
Intent intent = new Intent(PostActivity.this, Home.class);
startActivity(intent);
Toast.makeText(PostActivity.this, "Posted", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
}
}
You need to create a File
from the image path for the putFile(..)
method. Check the following official example from Firebase.
// File or Blob
file = Uri.fromFile(new File("path/to/mountains.jpg"));
// Create the file metadata
metadata = new StorageMetadata.Builder()
.setContentType("image/jpeg")
.build();
// Upload file and metadata to the path 'images/mountains.jpg'
uploadTask = storageRef.child("images/"+file.getLastPathSegment()).putFile(file, metadata);
// Listen for state changes, errors, and completion of the upload.
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");
}
}).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
Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
}
});
If you have an image in Uri
you can store it without converting using method like this:
private void uploadImage(Uri file) {
if (file != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference ref = storage.getReference().child("images/myPath/");
ref.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(FileUploadPage.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(FileUploadPage.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
To get Uri
from Intent
you can use code like this:
In your first activity put you image Uri
as extra: intent.putExtra("imgUrl", uri.toString());
Then on second activity:
Intent intent = getIntent();
Uri path;
if (intent.hasExtra("imgUrl")) {
path = Uri.fromFile(new File(getIntent().getStringExtra("imgUrl")));'
}
uploadImage(path);
Uri.fromFile(new File(String path)
should to protect you from wrong Uri
decoding.
Since you have a path, you can create an Uri
and upload it
filpath.putFile(Uri.fromFile(new File("/sdcard/cats.jpg"))).addOnSuccessListener(....
Also if you have a big file, you should create the Uri
async.
You should add a FailureListener
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
}
});
In this way, you can see what is wrong with your upload.
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.