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
Related
Is there any way to remove the link and only get the file name of the file in the code? Im trying to access to load a model in my app that is created in android studio
This one doesn't work because it provides a link instead the name of the file
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference modelRef = storage.getReference().child(myPlants.getPlantModel());
This code works
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference modelRef = storage.getReference().child(pre4.glb);
Is there a way to get the file name only and not the token? Please help.
The assigned text in the getPlantModel is the link.
Database Screenshot
public class PlantAR extends AppCompatActivity {
private ProgressDialog progressDialog;
Button downloadButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plant_ar);
Intent intent = getIntent();
MyPlants myPlants = (MyPlants) intent.getSerializableExtra("plants");
FirebaseApp.initializeApp(this);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference modelRef = storage.getReference().child("pre6.glb");
ArFragment arFragment = (ArFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragmentAR);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Model downloading Please Wait...........");
downloadButton = findViewById(R.id.downloadModel);
findViewById(R.id.downloadModel)
.setOnClickListener(v -> {
try {
File file = File.createTempFile("pre6", "glb");
progressDialog.show();
modelRef.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
buildModel(file);
}
});
} catch (IOException e) {
e.printStackTrace();
}
});
arFragment.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> {
AnchorNode anchorNode = new AnchorNode(hitResult.createAnchor());
anchorNode.setRenderable(renderable);
arFragment.getArSceneView().getScene().addChild(anchorNode);
});
}
private ModelRenderable renderable;
private void buildModel(File file) {
RenderableSource renderableSource = RenderableSource
.builder()
.setSource(this, Uri.parse(file.getPath()), RenderableSource.SourceType.GLB)
.setRecenterMode(RenderableSource.RecenterMode.ROOT)
.build();
ModelRenderable
.builder()
.setSource(this, renderableSource)
.setRegistryId(file.getPath())
.build()
.thenAccept(modelRenderable -> {
downloadButton.setVisibility(View.GONE);
progressDialog.dismiss();
Toast.makeText(this, "Model built", Toast.LENGTH_SHORT).show();;
renderable = modelRenderable;
});
}
I'm newbie for android and flutter development, I want to ask something about push notification, I build firebase_messaging by own self because its not support big notification image
The problem is I cant get the _url
int _selectedTab = 1;
static String _url = "";
static const platform =
const MethodChannel('com.example.loop_app_flutter_v2');
#override
Future<void> _firebaseMessageListener() async {
String getRedirect;
String url;
try {
final String result =
await platform.invokeMethod('getFirebaseMessagePayload');
getRedirect = '$result';
Map<String, dynamic> notif = jsonDecode(getRedirect);
url = notif["url"]; //payload success and url show up
} on PlatformException catch (e) {
getRedirect = "Failed : '${e.message}'.";
}
this.loadNotificationData(getRedirect);
setState(() {
_url = url; // i want to assign url to _url and put in List Widget
print(url); //print show up url
});
}
#override
void initState() {
_firebaseMessageListener();
}
final List<Widget> _children = [
new MainArtikel(),
new Webpage(url: _url),
new FeedBack(),
new Setting()
];
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.