'file.existsSync()': is not true
Asked Answered
M

2

5

I am going to store an image in firebase storage. When I send file through image picker then its working fine. But when I manually pass link of image then it is showing an error that says:

'package:firebase_storage/src/storage_reference.dart': 
Failed assertion: line 62 pos 12: 'file.existsSync()': is not true.

I am writing following code:

File image =  File("assets/img/pic.jpg");

final StorageReference firebaseStorageRef =
        FirebaseStorage.instance.ref().child('image');

InkWell(
            child: Text("Tap to Upload"),
            onTap: () {
              firebaseStorageRef.putFile(image);
            },
          ),
Magog answered 11/7, 2020 at 5:11 Comment(1)
You can't use File with assets as they aren't real files. If you want to upload an asset, load the asset into memory using RootBundle then use putData instead of putFile.Execrative
S
9

The error says it, the file doesn't exists, before doing that you should check if the file is there or create it if it's not

InkWell(
   child: Text("Tap to Upload"),
   onTap: () async {
     File image = await File("assets/img/pic.jpg").create(); 
     // it creates the file,
     // if it already existed then just return it
     // or run this if the file is created before the onTap
     // if(image.existsSync()) image = await image.create();
     firebaseStorageRef.putFile(image);
   },
),

Also I'm not sure if you can change/create files in the assets folder, if that doesn't work maybe try to put the file in a temp directory of your app

Slovak answered 11/7, 2020 at 6:22 Comment(0)
A
3

The Assets in Flutter are not directly accessible as File objects. To upload an image from the assets folder to Firebase Storage, you have to upload it to memory first using RootBundle, you can use the putData method instead of putFile.

Here's an updated version of your code:

final imageBytes = await rootBundle.load('assets/img/pic.jpg');
final imageData = imageBytes.buffer.asUint8List();

final StorageReference firebaseStorageRef =
        FirebaseStorage.instance.ref().child('image');

InkWell(
    child: Text("Tap to Upload"),
    onTap: () {
        firebaseStorageRef.putData(imageData);
            },
       ),
Amii answered 15/7, 2023 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.