Flutter - Get all images from firebase storage - android

I am manually upload my images to firebase storage console in web. I want to download all images to my flutter android app. But it is getting only one image at a time with getDownloadUrl() method.
In android, listAll() method List all items (files) and prefixes (folders) under this StorageReference.
Like this, anyone suggest me in flutter.
I saw stack over flow answers like there is no api for download all images at once. But any suggestion/ideas would be great.

Finally got the solution.
Flutter package firebase_storage: ^3.0.6 has no method called listAll(). Only able to get single file/image download url using getDownloadURL() method from firebase storage.
Recently (19 hours ago, 16th Oct 2019) flutter team has added this functionality to get all files and folders using listAll() method. Below is the git link.
https://github.com/FirebaseExtended/flutterfire/pull/232
Need to use package in pubspec.yaml like below :
firebase_storage:
git:
url: git://github.com/danysz/flutterfire.git
ref: master
path: packages/firebase_storage
This is temporary solution until they update this package version firebase_storage: ^3.0.6
Example Code :
void getFirebaseImageFolder() {
final StorageReference storageRef =
FirebaseStorage.instance.ref().child('Gallery').child('Images');
storageRef.listAll().then((result) {
print("result is $result");
});
}
Hope it will be useful for many people. Happy coding!

in my cause this code is work me.. for every unique user and get list of images.. you can specify your reference path then get list of images
Tested image
static Future<List<Map<String, dynamic>>> fetchImages(
String uniqueUserId) async {
List<Map<String, dynamic>> files = [];
final ListResult result = await FirebaseStorage.instance
.ref()
.child('Gallery')
.child('images')
.child(uniqueUserId)
.list();
final List<Reference> allFiles = result.items;
print(allFiles.length);
await Future.forEach<Reference>(allFiles, (file) async {
final String fileUrl = await file.getDownloadURL();
final FullMetadata fileMeta = await file.getMetadata();
print('result is $fileUrl');
files.add({
'url': fileUrl,
'path': file.fullPath,
'uploaded_by': fileMeta.customMetadata['uploaded_by'] ?? 'Nobody',
'description':
fileMeta.customMetadata['description'] ?? 'No description'
});
});
return files;
}

if only need specific images you can use the Image.network(url) method for retrieving the image. only thing you have to done is you have to copy the access token related to your specific image and paste it inside the Image.newtork(url). remember to cover the url with '' .
otherwise you can use the method below
Future downloadImage()async{
StorageReference _reference=FirebaseStorage.instance.ref().child("images/$_imageName.png");
String downloadAddress=await _reference.getDownloadURL();
setState(() {
_downloadUrl=downloadAddress;
});
}
now you can use the retrieve the image using Image.network(_downloadUrl).

Related

I want that await method will return or update the value first then go to next line in flutter

I am using firebase storage to upload image and i need first that image upload to storage and then donwload url set to imageUrl String url. So that i can pass it into api call. But by using await method its skipped that line of code and moves ahead. And URL is updating after api call.
I have attached the code image for best understanding.
Try this:
await uploadTask.snapshot.ref.getDownloadURL()
.then((value) => setState(() {
isModifyPhoto = true;
imageUrl = value;
}));
I did it by making onTap() method async and await uploadprofile() method call. Its working good now.

Why i see Lost device connection message when open gallery using image_picker?

I have a problem using image_picker on flutter in real device with android. When i open gallery using ImageSource.gallery the first screen is "Recent pictures", i can select any picture and everything fine, but if i open the gallery i see "Lost device connection" message and white screen.
_procesImage(ImageSource image) async {
final ImagePicker picker = ImagePicker();
file = await picker.pickImage(source: image);
setState(() {});
}
I beleive you're having trouble with iOS as you're talking about gallery but could you give more detail ? Is it happening on emulator or real device?
I would suggest you to doublecheck iOS specific authorizations in plist, also check if you're asking for storage permission before opening the gallery.
I had that kind of issue month ago but my library wasn't up to date and I guess updating it fixed the issue
Try to define methods like these and specifically point out from which location you want to access the image. Currently, it is not specified.
final ImagePicker imagePicker = ImagePicker();
_imgFromCamera() async {
final image = await imagePicker.pickImage(
source: ImageSource.camera);
// the further functionality here
sendImageToServer(image);
}
_imgFromGallery() async {
final image = await imagePicker.pickImage(
source: ImageSource.gallery);
// the further functionality here
sendImageToServer(image);
}

Flutter: Show PDF cover image

I want to show the cover page of a pdf. But I don't know how to proceed. I have the URL of the pdf file and I want to display the front page like an image. I am using the pdf library but I don't know how to proceed.
I was also looking for the same a few days ago and found solution for it.
You can use this package:https://pub.dev/packages/pdf_render
you can use it like this in your widget:
import 'package:pdf_render/pdf_render_widgets2.dart';
...
PdfDocumentLoader(
assetName: 'assets/hello.pdf',
filePath: 'path of the file in local storage',
pageNumber: 1,
pageBuilder: (context, textureBuilder, pageSize) => textureBuilder()
)
In the pdf_thumbnail package, it uses pdfx package to get every single page.
Relevant line in the library.
final page = await document.getPage(pageNumber);
final pageImage = await page.render(
width: page.width,
height: page.height,
);
images[pageNumber] = pageImage!.bytes;
await page.close();
There is a sample Futter wrapper for a PDF SDK here https://github.com/PDFTron/pdftron-flutter. And a corresponding blog: https://www.pdftron.com/blog/flutter/build-a-document-viewer-in-flutter/

How can I retrieve a file from the file system using React Native, for conversion to base64 and http posting as JSON?

I am using the react native template from this article. The code is all available on Github here.
You can use the app to record audio and save to the file system. I figured out how to retrieve the file URIs, but I'm finding it impossible to get the actual contents of the file itself. All I want to do is retrieve the actual file contents as a binary or ascii or hex string or whatever (it's a .m4a file), so I can convert it to base64 encoding and then post it as JSON to my server. Here's what my code looks like:
/src/screens/RecordAudioScreen/RecordAudioScreenContainer.js
onEndRecording: props => async () => {
try {
// here is the URI
console.log("HERE IS THE URI!!");
const audio_data = "URI: " + props.recording._uri;
// Help needed here
// retrieve file contents from the Android/iOS file system
// Encode as base64
audio_data = ... // ???????
// this works already, posts to the server
fetch("https://myserver.com/accept_file",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({user_id: 1, audio_data: audio_data})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) });
console.log("FINISHED POST REQUEST!!!")
await props.recording.stopAndUnloadAsync();
await props.setAudioMode({ allowsRecordingIOS: false });
} catch (error) {
console.log(error); // eslint-disable-line
}
if (props.recording) {
const fileUrl = props.recording.getURI();
props.recording.setOnRecordingStatusUpdate(null);
props.setState({ recording: null, fileUrl });
}
},
I've already tried a bunch of stuff with no success. Ideally I just get the file contents from the File system, convert to base64 and post it off all in this method just in javascript, but this is seemingly very difficult for what should be a pretty standard thing to do in an app based framework.
Here's some stack overflow questions on React Native Fetch Blob which I couldn't make work Fetch Blob 1 Fetch Blob 2
I've tried using React Native Fs, but I can't get it to load properly, I got super bogged down in stuff I didn't understand after trying to eject the app. I'd prefer a plain React Native solution if possible.
I've also tried some code using FormData but couldn't get that to work either.
Maybe the answer is kind of like this question about retrieving images from firebase? I don't know, this is my first attempt at doing anything in React.
It might also have something to do with the "file://" prefix in the URI that gets generated because there's a lot of questions discussing removing that (only for Android, or only for iOS I'm not too clear).
Converting to base64 will be done with something like this, but I need the actual file contents first:
Very appreciative of any help.
Some time ago I wrote a simple example of a record voice app.
To get the files I used this method:
import RNFS from 'react-native-fs';
(...)
getFiles() {
RNFS.readDir(AudioUtils.DocumentDirectoryPath)
.then((result) => {
this.setState({recordedFiles: result});
return Promise.all([RNFS.stat(result[0].path), result[0].path]);
})
.catch((err) => {
console.log(err.message, err.code);
});
}
It worked just fine.
Here's the full example https://github.com/soutot/react-native-voice-record-app
Let me know if it helped. Otherwise we can try a different approach

Ionic, upload image or string to firebase not working on Android, but working in browser and iOS

since about 3 days I am trying to upload an image to the firebase storage without success.
I tried several approaches I found here in stackoverflow.
It is even not possible to upload a simple string for Android.
Running the app in the browser is working fine for images and strings.
Emulator and phone returns the same error:
Firebase Storage: An unknown error occurred, please check the error payload for server response.
I don't know where should I check the mentioned "payload"
This is my code for uploading the string:
EDIT: I changed the function which retrieves the error to
alert(error.serverResponse);
this returns following Error message: "Multipart body does not contain
2 or 3 parts"
$scope.upload = function() {
//storage reference
var storage = firebase.storage();
//path reference
var storageRef = storage.ref();
var uploadTask = storageRef.child('testfile.png').putString("any string").then(function(snapshot) {
console.log('upload successful');
alert('ok');
}, function (error) {
// Handle unsuccessful uploads
//alert(error.message);
alert(error.serverResponse);
});
The function added below can help you to add an image on firebase where(file is the image you wish to add ).
$scope.addImage = function(file){
var fileRef = storageRef.child(file.name);
fileRef.put(file).then(function (snapshot) {
console.log(snapshot)
});
};

Categories

Resources