Take a photo and saving the photo to storage fails - flutter

I am using the camera plugin to take a picture like this:
image = await cameraController.takePicture()
It is working great and I can display this image in a preview. Now I want to store the picture to the device, and I am trying this:
Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
String appDocumentsPath = appDocumentsDirectory.path;
String filePath = '$appDocumentsPath/images/${image!.name}';
await File(image!.path).copy(filePath);
Then I get this error:
Unhandled Exception: FileSystemException: Cannot copy file to '/data/user/0/dk.hempelfonden.frontier/app_flutter/images/CAP8310428751941012175.jpg', path = '/data/user/0/dk.hempelfonden.frontier/cache/CAP8310428751941012175.jpg' (OS Error: No such file or directory, errno = 2)
What am I missing here?
Thank you
Søren

path is the directory /data/user/0/dk.some.app/cache/CAP7304644252296628120.jpg. Try adding a /filename.jpg or .png to it.
Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
String appDocumentsPath = appDocumentsDirectory.path;
String filePath = '$appDocumentsPath/images/$name.png';
logDebug('Saving from: ${_image!.path}');
logDebug('Copy to: $filePath');
return await File(_image!.path).copy(filePath+".jpg");

I think you trying to copy .png file to .jgp path that is why you are facing
FileSystemException try same image type for both image paths.

I was trying to copy the image file to a directory that was not existing, added this code:
String dirPath = '$appDocumentsPath/images';
await Directory(dirPath).create(recursive: true);

you have not created the file. so thats why its show you error
File newFile = File(await filePath);
if (newFile.existsSync()) {
await newFile.delete(); // Delete File first
}
newFile.createSync(recursive: true); // Create Again

Related

FileSystemException: Cannot open file, path = 'storage/emulated/0/DCIM/docs/myPdf.pdf' (OS Error: Operation not permitted, errno = 1)

I am trying to create a pdf document and write my data in that file. The data is a list of int or uint type. Able to do the same for images but not pdf or doc file. All permissions are given and it works for images. My code is below -
Future <File> createDocFile(Uint8List fileData, String type) async
{
File file = new File(".pdf");
if(await PermissionHandler.checkPermission(Permission.storage)!=true){
Url.toastShow("Storage permission not found.");
await Permission.storage.request();
}
else {
await file.writeAsBytes(fileData);
print("PDF SAVED IN DEVICE");
Url.toastShow("PDF saved in device",Colors.green);
}
}
Whenever you create a new file the device can't automatically find it. You'd have to manually tell the device to refresh for the files. Before you'd have to refresh all the files in the device for it to get updated which was very inefficient, but now you could just send the path of the file that you want to get updated. You can use the media_scanner plugin to do so.
Or If you wanna do it yourself with kotlin then here's the code,
private fun broadcastFileUpdate(path: String){
context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(File(path))))
}

Flutter create a file and write its contents

I am working on an app which gathers text content from server and as the next step I am trying to save them into separate files to be saved with in apps storage. Storage is a folder called 'storage'. Inside storage, there is a 'fileList.txt' file which contains the list of files.
In pubspec.yaml I declared this folder in the assets as follows:
assets:
- storage/
And I can read it using the following function:
Future<String> readFileContent() async {
String response;
response =
await rootBundle.loadString('storage/fileList.txt');
return response;
}
To save the file I made use of online examples which use 'path_provider' package. However when I try to save one of the downloaded files for instance 'file4.dat' using the following functions, I encounter the following error. How can I resolve that problem?
saveFileLocally() async {
await _writeFile();
}
Future<Null> _writeFile() async {
await (await _getLocalFile()).writeAsString(vars.fileContents);
}
Future<File> _getLocalFile() async {
// get the path to the document directory.
String dir = (await PathProvider.getApplicationSupportDirectory()).path;
print('DIR :::: ' + dir);
return new File(
'$dir/storage/files/file' + vars.newFileID.toString() + '.dat');
}
The error is:
Unhandled Exception: FileSystemException: Cannot open file,
path = '/data/user/0/com.example.ferenova_flutter_app/files/storage/file4.dat'
(OS Error: No such file or directory, errno = 2)
Thanks guys and take care !!! :)
While checking out path_provider examples, I ran into this important detail:
Directory directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory(); //FOR iOS
This solved my problem. I am no longer using default rootBundle asset to process any external files.
I think you should check your paths.
storage/fileList.txt is not the same as $dir/storage/files/file' + vars.loadedFileID.toString() + '.dat'
you should try:
response =
await rootBundle.loadString('$dir/storage/files/file' + vars.loadedFileID.toString() + '.dat'');
Or something similar.
GL

Read an online text file and put it into a variable

I want to check an online txt file for the newest version code and show a dialog which says "Please update" or something similar. Is it posiible to put the content of the file into a variable?
EDIT: I tried Arpit Awasthi's solution but I get these errors:
lib/main.dart:685:25: Error: Method not found: 'HttpClient'.
var request = await HttpClient().getUrl(Uri.parse(url));
^^^^^^^^^^
lib/main.dart:687:23: Error: Method not found: 'consolidateHttpClientResponseBytes'.
var bytes = await consolidateHttpClientResponseBytes(response);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
lib/main.dart:688:5: Error: 'Directory' isn't a type.
Directory appDocDir = await getApplicationDocumentsDirectory();
^^^^^^^^^
lib/main.dart:690:5: Error: 'File' isn't a type.
File file = File("${appDocDir.path}/$fileName");
^^^^
lib/main.dart:690:17: Error: Method not found: 'File'.
File file = File("${appDocDir.path}/$fileName");
^^^^
lib/main.dart:691:5: Error: 'File' isn't a type.
File urlFile = await file.writeAsBytes(bytes);
^^^^
You can use the following function to download the file and then get the File object of that file.
static downloadFile(String url) async{
var request = await HttpClient().getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
Directory appDocDir = await getApplicationDocumentsDirectory();
String fileName = ('yourFileName.fileExtention');
File file = File("${appDocDir.path}/$fileName");
File urlFile = await file.writeAsBytes(bytes);
return urlFile;
}
Note :- I've used this plugin to get app folder path :- path_provider: ^1.6.18
Basically, what you can do is the following.
You May Define in a variable (context probably) you Current Version...
The you a async http request, you can call to an API where you check your latest release and if it is > that current one, trigger an alert dialog that shows that There is a new version available.

I have issues with the path on the getApplicationDocumentsDirectory() function

I get an error message over the path provider that says
error: The getter 'path' isn't defined for the class 'Future'.
I am trying to generate a PDF file following the https://pub.dev/packages/pdf#-example-tab- and this example https://github.com/javico2609/flutter-challenges/blob/master/lib/pages/code_examples/pdf_and_csv/pdf.dart
But as I go on I get the error that path isn't defined on the Future. But as I see on the web I am doing it right. Here is the code:
final String dir = (getApplicationDocumentsDirectory()).path;
final String path = '$dir/receta.pdf';
final File file = File(path);
file.writeAsBytesSync(newpdf.save());
As I said. I can't run the app because I get the message error: The getter 'path' isn't defined for the class 'Future'.
Also tried to write
final Future<Directory> directory = getApplicationDocumentsDirectory();
final String dir = directory.path;
final String path = '$dir/receta.pdf';
final File file = File(path);
file.writeAsBytesSync(newpdf.save());
But it doesn't work, path on the variable dir shows the error
In final Future<Directory> directory = getApplicationDocumentsDirectory(); getApplicationDocumentsDirectory() is any async function which means it will return the directory asynchronously , So then when you are trying to read directory.path;, directory is not initialized yet, its null.
Instead returning a future directory wait till it is initialized,
final Directory directory = await getApplicationDocumentsDirectory();
Import this.. it solves the issue
import 'package:path_provider/path_provider.dart';
You must put await keyword like this:
final directory = await getApplicationDocumentsDirectory();
final path = join(directory.path, 'db_todolist_sqflite');

How to get all mp3 files from internal as well as external storage in Flutter?

I want to show all songs in listview with flutter project but i dunno, how to access my internal folder.
first of all
I have just created a folder with name 'Shruti' but it is created at /storage/emulated/0/Android/data/com.example.musicplayer/files' but i want to that folder only at /storage/emulated/0/ path.
Because i don't know, how to read & write to internal as well as external storage .
final directory = await getApplicationDocumentsDirectory();
print('Directory= $directory');
// External storage directory: /storage/emulated/0
Directory externalDirectory = await getExternalStorageDirectory();
print('External Storage:$externalDirectory ');
new Directory(externalDirectory.path+'/'+'Shruti').create(recursive: true)
.then((Directory directory) {
print('Path of New Dir: '+directory.path);
});
This code can be used to read storage. Your have to specify the path.
Directory dir = Directory('/storage/emulated/0/');
String mp3Path = dir.toString();
print(mp3Path);
List<FileSystemEntity> _files;
List<FileSystemEntity> _songs = [];
_files = dir.listSync(recursive: true, followLinks: false);
for(FileSystemEntity entity in _files) {
String path = entity.path;
if(path.endsWith('.mp3'))
_songs.add(entity);
}
print(_songs);
print(_songs.length);
P.S. :- Don't forget the permissions though.
You can also check this package for other features.
https://pub.dev/packages/flutter_audio_query
You can use the flute_music_player package to get the songs.