I have been searching for this problem, but I have not found any solution here. My problem is that when I post new item to firebase storage everything works well, but when I try to download it, directory folder is created successfully, but file is not downloaded as it shows me this error exception:
com.google.firebase.storage.StorageException: Object does not exist at
location
My code here:
#Override
public void onButtonDownloadClick(View view, final int position) {
String name = list.get(position).getRemoteName();
File storagePath = new File(Environment.getExternalStorageDirectory(), "FromFiles");
// Create direcorty if not exists
if(!storagePath.exists()) {
storagePath.mkdirs();
}
final File myFile = new File(storagePath, list.get(position).getRemoteName());
islandRef = storageReference.child(uid).child("files").child(name);
islandRef.getFile(myFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
Toast.makeText(getActivity(), "Succeed", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Toast.makeText(getActivity(), exception.toString(), Toast.LENGTH_LONG).show();
}
});
}
});
When I press button, file should be downloaded, however only directory is created.
This is working example for the firebase download and check the download path, the object should exist in the bucket.
// Initialize Storage
//storage
mStorage = FirebaseStorage.getInstance("gs://<bucket_name>");
mStorageRef = mStorage.getReference();
final StorageReference downloadRef;
downloadRef = mStorageRef.getRoot().child(downloadPath);
try {
File output = new File(Environment.getExternalStorageDirectory() + File.separator + Config.MY_VIDEOS_PATH);
if (!output.exists()) {
output.mkdir();
}
localFile = new File(output, downloadId);
} catch (Exception e) {
e.printStackTrace();
}
// Download and get total bytes
downloadRef.getFile(localFile)
.addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onProgress(FileDownloadTask.TaskSnapshot taskSnapshot) {
showProgressNotification(1,title, "",
taskSnapshot.getBytesTransferred(),
taskSnapshot.getTotalByteCount());
}
})
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "download:SUCCESS");
// Send success broadcast with number of bytes downloaded
broadcastDownloadFinished(downloadPath, taskSnapshot.getTotalByteCount());
showDownloadFinishedNotification(downloadPath, (int) taskSnapshot.getTotalByteCount());
// Mark task completed
taskCompleted();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.w(TAG, "download:FAILURE", exception);
Log.w(TAG, "download:FAILURE", exception.getCause());
// Send failure broadcast
broadcastDownloadFinished(downloadPath, -1);
showDownloadFinishedNotification(downloadPath, -1);
// Mark task completed
taskCompleted();
}
});
Let us assume that your image.jpg in the photos folder then the downloadPath photos/image.jpg
Check Firebase Rules ..!
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
private FirebaseAuth mAuth;
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseReference;
StorageReference mFStorage;
StorageReference filePath;
mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseReference = mdatabase.getReference();
mFStorage= FirebaseStorage.getInstance().getReference();
filePath=mFStorage.child("audio").child(audioId+".mp3");
filePath.putFile(imageGalleryUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
dialog.dismiss();
DownloadUrl=taskSnapshot.getDownloadUrl();
Log.d(TAG,"DownloadUrl.toString()");
//download link for file
}
});
then use Download Manager To download File like for Audio
Context ctx=MainActivty.this;
DownloadManager downloadManager = (DownloadManager)ctx.getSystemService(DOWNLOAD_SERVICE);
//Your Url here
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDescription("Downloading a file");
long id = downloadManager.enqueue(request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("File Downloading...")
.setDescription("Audio File Downloading...!")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/Audio/"+audioName+".mp3"));
Related
I am downloading files from firebase storage
But I can only download one by one
Can I download multiple files at once?
Is it the best way to repeat the same code?
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
StorageReference islandRef = storageRef.child(filename);
final String saveFilename = filename;
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/down/");
// If no folders
if (!dir.exists()) {
dir.mkdirs();
}
final File localFile = new File(dir,saveFilename);
islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
Simply call putFile once for each file you want to download. You will need a different reference and local file for each call.
FileDownloadTask task1 = storageRef1.getFile(localFile1);
FileDownloadTask task2 = storageRef2.getFile(localFile3);
FileDownloadTask task3 = storageRef3.getFile(localFile3);
You can then wait for all them to complete with Tasks.whenAll():
Tasks.whenAll(task1, task2, task3)
.addOnSuccessListener(new OnSuccessListener<List<Task<*>>() {
#Override
public void onSuccess(Task task) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
There is no specific API to download multiple files. You'll just have to download them by calling the same API for each file.
I have used this library in my Android app
implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-firestore:20.0.0'
implementation 'com.google.firebase:firebase-storage:18.0.0'
And this method use to upload my image on Firebase Storage:
StorageReference storageRef = mStorage.getReference();
finalStorageReference mountainsRef = storageRef.child("myImgName");
Uri file = Uri.fromFile(new File(myImgName));
UploadTask uploadTask = mountainsRef.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Log.e(TAG, "img Error :" + exception.getMessage());
//Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
//Log.e(TAG, "Task :" + taskSnapshot.getTask());
//Log.e(TAG, "Class Store:" + taskSnapshot.getStorage().getDownloadUrl());
Log.e(TAG,"metaData :"+taskSnapshot.getMetadata().getPath());
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
}
}).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 + "%");
}
});
this code perfectly working for me to upload image. but how to know the image location url ?
To get the download URL for a file in Cloud Storage, you call getDownloadUrl() on the StorageReference to that file. getDownloadUrl() returns a task, so you'll need to add a success listener to get the result.
mountainsRef.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png' in uri
System.out.println(uri.toString());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
For more on this, see:
the sample in the documentation on uploading a file
the documentation on downloading a file
How to use getdownloadurl in recent versions?
You can find your project's URL at the top of the Files section of Storage in the Firebase Console
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://example-firebase.appspot.com").child("android.jpg");
You can create a File object and attempt to load the file you want by calling getFile on your StorageReference with the new File object passed as a parameter. Since this operation happens asynchronously, you can add an OnSuccessListener and OnFailureListener
try {
final File localFile = File.createTempFile("images", "jpg");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
mImageView.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch (IOException e ) {}
You can get the file's Url by using the getDownloadUrl() method on your StorageReference, which will give you a Uri pointing to the file's location.
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.e("Image +", "uri: " + uri.toString());
//Handle whatever you're going to do with the URL here
}
});
I have created an app running with Firebase Storage. The idea is that you select an Image from your Photo Gallery and then Upload it to Firebase Storage. The connection with Firebase seems to work fine, I can select an Image. The problem arises when I push the Submit Button to upload it to Firebase.
When I click it one time, nothing happens.
When I click it a few times, I get the message "an unknown error occurred, please check the HTTP result code and inner exception"..
What should I do, looking for advice..
From the Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
From the Activity:
public class PostActivity extends AppCompatActivity {
private static final int GALLERY_REQUEST = 2;
private Uri uri = null;
private ImageButton imageButton;
private EditText editName;
private EditText editDescription;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
//reference the two edittext Views, initialize them
editName = (EditText) findViewById(R.id.editName);
editDescription = (EditText) findViewById(R.id.editDescription);
//add the reference to the storagereference, initialize it
storageReference = FirebaseStorage.getInstance().getReference();
}
public void ImageButtonClicked (View view){
Intent galleryintent = new Intent (Intent.ACTION_GET_CONTENT);
galleryintent.setType("Image/*");
startActivityForResult(galleryintent, GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
uri = data.getData();
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setImageURI(uri);
}
}
public void submitButtonClicked (View view){
String titleValue = editName.getText().toString().trim();
String titleDescription = editDescription.getText().toString().trim();
if (!TextUtils.isEmpty(titleValue) && !TextUtils.isEmpty(titleDescription)){
StorageReference filePath = storageReference.child("PostImage").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadurl = taskSnapshot.getDownloadUrl();
Toast.makeText(PostActivity.this,"uploadcomplete",Toast.LENGTH_LONG).show();
}
});
filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
Try this method for image upload to firebase storage:
private void uploadMethod() {
progressDialog();
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReferenceProfilePic = firebaseStorage.getReference();
StorageReference imageRef = storageReferenceProfilePic.child("Your Path" + "/" + "Image Name" + ".jpg");
imageRef.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successful
//hiding the progress dialog
//and displaying a success toast
dismissDialog();
String profilePicUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successful
//hiding the progress dialog
dismissDialog();
//and displaying error message
Toast.makeText(getActivity(), exception.getCause().getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
// double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
// //displaying percentage in progress dialog
// progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
I have found an answer through the code of Rahul Chandrabhan.
What I have changed is to remove the last part of the following method:
StorageReference filePath =
storageReference.child("PostImage").child(uri.getLastPathSegment());
TO
StorageReference filePath = storageReference.child("PostImage");
To perform image upload on firebase use below method:
void uploadFile(String pathToFile, String fileName, String serverFolder, String contentType) {
if (pathToFile != null && !pathToFile.isEmpty()) {
File file = new File(pathToFile);
if (file.exists()) {
Uri uri = Uri.fromFile(new File(pathToFile));
// Create a storage reference from our app
mStorageRef = mFirebaseStorage.getReference();
// Create a reference to "mountains.jpg"
//StorageReference mountainsRef = storageRef.child(fileName);
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = mStorageRef.child(serverFolder+"/" + fileName);
StorageMetadata metadata = null;
if (contentType != null && !contentType.isEmpty()) {
// Create file metadata including the content type
metadata = new StorageMetadata.Builder()
.setContentType(contentType)
.build();
}
if (metadata != null) {
uploadFileTask = mountainImagesRef.putFile(uri, metadata);
} else {
uploadFileTask = mountainImagesRef.putFile(uri);
}
uploadFileTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
hideProgressDialog();
exception.printStackTrace();
Log.e(TAG,exception.getMessage());
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure(exception.getMessage());
}
}
});
uploadFileTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
hideProgressDialog();
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.e(TAG, "Upload is success "+ downloadUrl);
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadSuccess("Upload is success "+ downloadUrl.toString(), downloadUrl.toString());
}
}
});
// Observe state change events such as progress, pause, and resume
uploadFileTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
hideProgressDialog();
double progressPercent = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressPercent = Double.parseDouble(FirebaseUtil.formatDecimal(progressPercent,2));
Log.e(TAG, "File Upload is " + progressPercent + "% done");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadProgress(progressPercent);
}
}
});
uploadFileTask.addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
hideProgressDialog();
Log.e(TAG, "Upload is paused");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadPaused("Upload is paused");
}
}
});
}
else
{
hideProgressDialog();
Log.e(TAG, "Upload file does not exists");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure("Upload file does not exists");
}
}
}else
{
hideProgressDialog();
Log.e(TAG,"pathToFile cannot be null or empty");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure("pathToFile cannot be null or empty");
}
}
}
Make a call this method as below:
public void uploadDummyPicture(String email, String imagePath){
if (imagePath == null) {
return;
}
if (!isValidEmail(email)) {
return;
}
String serverFolder = "dummy_images/" + email; //path of your choice on firebase storage server
String fileName = "DummyPhoto.png";
uploadFile(imagePath, fileName, serverFolder, "image/png");
showProgressDialog();
}
Make sure to check the firebase storage rules before using above code as explained here. If the rules have firebase authentication required, then first complete firebase authentication of the current user and then start uploading the file.
I hope this answer will you solve your problem.
In my case, the URI which I was fetching on the onActivityResult function was just not in the right format.
Previously I was parsing like this
uri=Uri.parse(your image path)
but after changing to this it worked
uri=Uri.fromFile(new File(your image path))
the upload function
public void upload()
{
if(uri!=null)
{
progressBar.setVisibility(View.VISIBLE);
progressBar_tv.setVisibility(View.VISIBLE);
Log.i("URI",uri.getPath());
UploadTask uploadTask=sRef.putFile(uri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(VideoEditAndUploadActivity.this, "Upload Failed:"+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();;
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(VideoEditAndUploadActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
progressBar_tv.setVisibility(View.INVISIBLE);
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
updateUploadProgress(snapshot);
}
});
}
else{
Toast.makeText(this, "Video Uri is null: please choose a video first!", Toast.LENGTH_SHORT).show();
}
}
the update progress bar function
#SuppressLint("DefaultLocale")
private void updateUploadProgress(UploadTask.TaskSnapshot snapshot) {
long fileSize=snapshot.getTotalByteCount();
long uploadBytes=snapshot.getBytesTransferred();
long progress=(100*uploadBytes)/fileSize;
progressBar.setProgress((int) progress);
progressBar_tv.setText(String.format("%d%%", progress));
}
If you are using rxjava then you could use the following snippet
public Observable<FirebaseFile> uploadImageToFirebase(#NonNull Uri file) {
return Observable.create(emitter -> {
try {
final StorageReference conversationReference = reference.child("some-identifier");
final File localFile = new File(file.getPath());
final StorageReference fileReference = conversationReference
.child(UUID.randomUUID().toString().toLowerCase(Locale.ROOT) + "-" + localFile.getName());
final UploadTask uploadTask = fileReference.putFile(file);
uploadTask.continueWithTask(task -> {
if (task.isSuccessful()) {
return fileReference.getDownloadUrl();
} else {
if (task.getException() != null) {
throw task.getException();
} else {
throw new RuntimeException("Error uploading file to firebase storage");
}
}
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
final Uri downloadUri = task.getResult();
if (downloadUri != null) {
emitter.onNext(new FirebaseFile(file.getPath(), downloadUri.toString(), 100));
emitter.onComplete();
} else {
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("Error uploading stream to firebase storage"));
}
}
} else {
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("Error uploading file to firebase storage"));
}
}
});
uploadTask.addOnProgressListener(taskSnapshot -> {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
emitter.onNext(new FirebaseFile(file.getPath(), null, (int) progress));
});
} catch (Exception e) {
if (!emitter.isDisposed()) {
emitter.onError(e);
}
}
});
}
Where
FirebaseStorage fs = FirebaseStorage.getInstance()
and
StorageReference StorageReference = firebaseStorage.getReference("some-identifier-if-any");```
I'm having trouble uploading an image over firebase.
Here's the code:
//...
//Storage
mFirebaseStorage = FirebaseStorage.getInstance();
mUserphotos = mFirebaseStorage.getReference().child("user/#userID");
mTestphotos = mFirebaseStorage.getReference().child("user/testPhotos");
//...
public void uploadImage(Uri uri) {
Uri file = Uri.fromFile(new File("user/testPicture"));
StorageReference testPath = mTestphotos.child("images/"+file.getLastPathSegment());
UploadTask uploadTask = testPath.putFile(file);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, "failure", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(MainActivity.this, "It worked", Toast.LENGTH_SHORT).show();
}
});
//...
To save time yes I am sure the uri is getting the correct photo. There is also more to the uploadImage
//getting the storage reference
// filePath is Uri
// "uploads/" is STORAGE_PATH_UPLOADS
StorageReference sRef = storageReference.child("uploads/" + System.currentTimeMillis() + "." + getFileExtension(filePath));
//adding the file to reference
sRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//displaying success toast
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
//creating the upload object to store uploaded image details
Upload upload = new Upload(editTextName.getText().toString().trim(), taskSnapshot.getDownloadUrl().toString());
//adding an upload to firebase database
String uploadId = mDatabase.push().getKey();
mDatabase.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//displaying the upload progress
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
Try this,
Uri uri = data.getData() ;// your image uri
StorageReference imagePathReference = StorageRef.child("Your path");
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
// convert bitmap to byte array to save image in firebase storage
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (bmp != null) {
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bos);
}
byte[] dataNew = bos.toByteArray();
uploadTask = imagePathReference.putBytes(dataNew);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("firebase ", " addOnFailureListener ");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// u will et download url here.
}
});
private void uploadimage() {
progressbar.setMessage("Uploading Data");
progressbar.setCanceledOnTouchOutside(false);
progressbar.show();
String dateStamp = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSS").format(new Date()).toString();
final StorageReference imagepath = storageReference.child("Image" + dateStamp);
imagepath.putFile(selectedImage).addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//Toast.makeText(Dashboard.this, "Image Stored Succesfully", Toast.LENGTH_LONG).show();
getimage = taskSnapshot.getDownloadUrl();
// bmp = ((BitmapDrawable) imagepreview.getDrawable()).getBitmap();
Map<String,String> imagemap=new <String,String>HashMap();
imagemap.put("imageurl",getimage);
databaseReference.child(Table_Dashboard).push().setValue(imagemap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
imagepreview.setImageResource(R.mipmap.preview);
progressbar.dismiss();
Toast.makeText(Dashboard.this, "Image Uploaded Succesfully", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
use the above code. it works for me, Hope it will resolve your error
I uploaded a file to Firebase Storage from my project console. Now, I downloaded that file from my app using the method 'Download to a local file' as mentioned in the Firebase Storage documentation, but I am not able to find the downloaded file on my phone.
Can someone tell me where does that file get downloaded to?
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
final StorageReference storageReference = firebaseStorage.getReferenceFromUrl("gs://ldq-app-d2e6b.appspot.com");
button_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = new String(editText_file.getText().toString());
StorageReference childReference = storageReference.child("Quizzes");
StorageReference fileReference = storageReference.child("Quizzes/" + fileName + ".pdf");
File localFile = null;
try {
localFile = File.createTempFile(fileName, "pdf");
}
catch (IOException ioe){
Toast.makeText(getContext(), "File creation failed", Toast.LENGTH_SHORT).show();
}
fileReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getContext(),"File downloaded",LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(),"Download failed. Try again!", LENGTH_SHORT).show();
}
});
//Toast.makeText(getContext(),"Button working",LENGTH_SHORT).show();
}
});
As per Firebase Document, they are creating a temporary file for saving Image from Url. Link
File localFile = File.createTempFile("images", "jpg");
If you want to store it on phone's internal memory or in external memory then just create a File with storage path and pass it to FileDownloadTask.
File storagePath = new File(Environment.getExternalStorageDirectory(), "directory_name");
// Create direcorty if not exists
if(!storagePath.exists()) {
storagePath.mkdirs();
}
final File myFile = new File(storagePath,"file_name");
yourStorageRef.getFile(myFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});