I have an image which I got from a Canvas PictureRecorder. Now I want to upload it to Firebase storage. My issue is converting it to a png file to upload. I don't know much about converting images, so not sure how to manipulate it in a way to upload as a png file.
final picture = recorder.endRecording();
final img = picture.toImage(640, 360);
final pngBytes = await img.toByteData();
final Directory systemTempDir = Directory.systemTemp;
final File file = await new File('${systemTempDir.path}/foo.png').create();
file.write?????(pngBytes); <-- Not sure how to write the file here
final StorageReference ref =
storage.ref().child('images').child('image.png');
final StorageUploadTask uploadTask =
ref.putFile(file);
Got it!
final picture = recorder.endRecording();
final img = picture.toImage(640, 360);
final pngBytes = await img.toByteData(format: ImageByteFormat.png);
Uint8List finalImage = Uint8List.view(pngBytes.buffer);
final Directory systemTempDir = Directory.systemTemp;
final File file = await new File('${systemTempDir.path}/foo.png').create();
file.writeAsBytes(finalImage);
final StorageReference ref = storage.ref().child('images').child('image.png');
final StorageUploadTask uploadTask = ref.putFile(file);
You could use imagemagik to do your file conversions. This link gives you a reasonable amount of detail on how to do that so I won't dig in here. Alternatively, you could write a cloud function that does the conversions on the server. Depends on your use-case.
HTH.
Related
I'm writing an app that selects an image from gallery and uuploads into a folder in firestore.
await Future.forEach(_paths.entries, (v) async {
String uid = Uuid().v1();
StorageReference imgReference =
_storageReference.child("Form2").child(uid);
StorageUploadTask task = imgReference.putFile(
File(v.value)
);
StorageTaskSnapshot downloadURL = await
task.onComplete;
String value = await downloadURL.ref.getDownloadURL();
paths[uid] = value;
}
The image is not uploading into the folder. But it is uploading into the firestore directly
You'll have to specify the folder name in .child(). Like : .child("/$folder").child("$fileName").
Example :
StorageReference ref = FirebaseStorage.instance.ref().child('/$folder').child(fileName);
StorageUploadTask uploadTask = ref.putData(imageData);
print('Upload triggered in the background.');
...
return await (await uploadTask.onComplete).ref.getDownloadURL();
}
This is a code that upload an image with its name to firebase. Sliderutils is a class that has a getName() and getImageUrl() function (getters and setters).
StorageReference Ref=
mStorageRef.child(System.currentTimeMillis()+"."+getPath(filePath));
mStorageTask = Ref.putFile(filePath)
.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Image uploaded successfully.", Toast.LENGTH_LONG).show();
SliderUtils sliderUtils = new SliderUtils(EditTextName.getText().toString().trim(),
taskSnapshot.getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(sliderUtils);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this,"Image upload failed.",Toast.LENGTH_SHORT).show();
}
})
Accounting to firebase docs the easiest way is to add a child to storage reference:
uploadImageToFireStore(String foldername, String fileName) async {
// Upload image to firebase storage
final storageRef = FirebaseStorage.instance.ref().child("$foldername/$fileName");
await storageRef.putFile(imgPath!);
}
This function receive a folder name and file name to upload the file.
Hope this will help
Good luck
I am new to flutter and firebase,I want to upload PDF into firebase using flutter please help me to solve this by providing some resources or links..
Thanks in advance.
You can use this dependency https://pub.dev/packages/file_picker to upload any kind of file to database.
final mainReference = FirebaseDatabase.instance.reference().child('Database');
Future getPdfAndUpload()async{
var rng = new Random();
String randomName="";
for (var i = 0; i < 20; i++) {
print(rng.nextInt(100));
randomName += rng.nextInt(100).toString();
}
File file = await FilePicker.getFile(type: FileType.CUSTOM, fileExtension: 'pdf');
String fileName = '${randomName}.pdf';
print(fileName);
print('${file.readAsBytesSync()}');
savePdf(file.readAsBytesSync(), fileName);
}
Future savePdf(List<int> asset, String name) async {
StorageReference reference = FirebaseStorage.instance.ref().child(name);
StorageUploadTask uploadTask = reference.putData(asset);
String url = await (await uploadTask.onComplete).ref.getDownloadURL();
print(url);
documentFileUpload(url);
return url;
}
void documentFileUpload(String str) {
var data = {
"PDF": str,
};
mainReference.child("Documents").child('pdf').set(data).then((v) {
});
}
By this you can upload file to firebase storage and insert the url to realtime database.
I would like to upload video in Firebase Storage.
I tried like so.
Future uploadToStorage() async {
try {
final DateTime now = DateTime.now();
final int millSeconds = now.millisecondsSinceEpoch;
final String month = now.month.toString();
final String date = now.day.toString();
final String storageId = (millSeconds.toString() + uid);
final String today = ('$month-$date');
final file = await ImagePicker.pickVideo(source: ImageSource.gallery);
StorageReference ref = FirebaseStorage.instance.ref().child("video").child(today).child(storageId);
StorageUploadTask uploadTask = ref.putFile(file);
Uri downloadUrl = (await uploadTask.future).downloadUrl;
final String url = downloadUrl.toString();
print(url);
} catch (error) {
print(error);
}
}
But the problem is that I uploaded 3 different videos. one is from real device and the others are from Ios simulator and only one video from simulator was recognized as video like this image.
File: /Users/Daibaku/Library/Developer/CoreSimulator/Devices/C99406E4-12F3-480A-82A6-F6144ADD21AB/data/Containers/Data/Application/23E82E18-9293-4EEB-AEEA-6A873F2F7CD7/tmp/image_picker_0B59CC5B-BB53-4019-BA8E-5F219374D8C8-7394-000006A2FA530CD0.MOV'
File:
'/Users/Daibaku/Library/Developer/CoreSimulator/Devices/C99406E4-12F3-480A-82A6-F6144ADD21AB/data/Containers/Data/Application/23E82E18-9293-4EEB-AEEA-6A873F2F7CD7/tmp/image_picker_F9355517-8C5C-4804-9312-69E1696CAF87-7394-000006A80D46F0B7.MOV'
Those are file path from similator and bottom one was recognized as video.
Does anyone know what is happening and how to fix it?
Thank you!
Edit
sorry actually last one on the image was uploaded manually(I put into storage from my finder). So, both simulator and real device can't upload video.
I worked it out. The point is you have to specify the metadata content type manually like so.
Future uploadToStorage() async {
try {
final DateTime now = DateTime.now();
final int millSeconds = now.millisecondsSinceEpoch;
final String month = now.month.toString();
final String date = now.day.toString();
final String storageId = (millSeconds.toString() + uid);
final String today = ('$month-$date');
final file = await ImagePicker.pickVideo(source: ImageSource.gallery);
StorageReference ref = FirebaseStorage.instance.ref().child("video").child(today).child(storageId);
StorageUploadTask uploadTask = ref.putFile(file, StorageMetadata(contentType: 'video/mp4')); <- this content type does the trick
Uri downloadUrl = (await uploadTask.future).downloadUrl;
final String url = downloadUrl.toString();
print(url);
} catch (error) {
print(error);
}
}
In flutter, I want to get data from firebase realtime database and save it in local storage as json and populate list view from that json. If database updated in firebase ,then Json should get update and should reflect in list view.
DataSnapshot firebaseData;
File allnews_json;
Directory dir;
String allnews_filename = "allnews.json";
bool fileExists = false;
#override
void initState() {
super.initState();
getApplicationDocumentsDirectory().then((Directory directory) {
dir = directory;
allnews_json = new File(dir.path + "/" + allnews_filename);
fileExists = allnews_json.existsSync();
if (fileExists) this.setState(() => fileContent = JSON.decode(allnews_json.readAsStringSync()));
});
FirebaseDatabase.instance.reference().child('news')
.once()
.then((onValue) {
firebaseData = onValue.value;
write(firebaseData);
});
}
void write(DataSnapshot snapshot) async {
print("Creating file!");
File file = new File(dir.path + "/" + allnews_filename);
file.createSync();
final String key = snapshot.key;
final String headline = snapshot.value['title'];
final int news = snapshot.value['content'];
String content = '{"$key":{"headline":"$headline","news":"$news"}}';
file.writeAsStringSync(content);
}
This is the code i have so far. But there is something wrong in this too.
Is there a way to read an embedded JSON file in a PCL project with PCLStorage module? I looked everywhere but couldn't find a sample related to this matter.
EDIT: PCLStorage link: https://github.com/dsplaisted/pclstorage
you need something like this:
public static async Task<string> ReadFileContent(string fileName, IFolder rootFolder)
{
ExistenceCheckResult exist = await rootFolder.CheckExistsAsync(fileName);
string text = null;
if (exist == ExistenceCheckResult.FileExists)
{
IFile file = await rootFolder.GetFileAsync(fileName);
text = await file.ReadAllTextAsync();
}
return text;
}
to use:
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder myCoolFolder = await rootFolder.CreateFolderAsync("MyCoolForler", CreationCollisionOption.OpenIfExists);
string fileContent = await this.ReadFileContent("MyCoolFile.txt", myCoolFolder);
You should be able to read embedded resources like this:
var assembly = typeof(LoadResourceText).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.PCLTextResource.txt");
string text = "";
using (var reader = new System.IO.StreamReader (stream)) {
text = reader.ReadToEnd ();
}
Xamarin has a great guide on how to work with them here.
https://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/files/