FilePicker Unhandled Exception: FileSystemException: Cannot copy file to 'Directory: - flutter

` onPressed: () async {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path.toString());
} else {
// User canceled the picker
}
if (result != null) {
PlatformFile file = result.files.first;
print('222222222222222222222222221');
print(file.name);
print("5555555555555555555555555555555");
print(file.bytes);
print(file.size);
print(file.extension);
print("6666666666666666666666666");
print(file.path);
final newFile = await saveFilePermanently(file);
} else {
// User canceled the picker
}
}, `
` Future<File> saveFilePermanently(PlatformFile file) async{
final appStorage = await getApplicationDocumentsDirectory();
final newFile = File('${appStorage}/${file.name}');
return File(file.path!).copy(newFile.path);
} `
i got this error
E/flutter ( 833): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FileSystemException: Cannot copy file to 'Directory: '/data/user/0/com.sangvaleap.online_course/app_flutter'/X2Download.com - Imagine Dragons x J.I.D - Enemy (from the series Arcane League of Legends) (128 kbps).mp3', path = '/data/user/0/com.sangvaleap.online_course/cache/file_picker/X2Download.com - Imagine Dragons x J.I.D - Enemy (from the series Arcane League of Legends) (128 kbps).mp3' (OS Error: No such file or directory, errno = 2)

Related

Converting PlatformFile to File

I am using the package file_picker to select a PDF file from the device and uploading it to a remote server.
void capturarPDF() async{
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if(result == null) return;
PlatformFile file = result!.files.first ;
print("file ${file.path}");
_upload(file);
}
void _upload(File file) {
if (file == null) return;
setState(() {});
String base64Image = base64Encode(file.readAsBytesSync());
String fileName = file.path!.split("/").last;
String? mimeStr = lookupMimeType(file.path.toString());
var fileType = mimeStr!.split('/');
var tipo = "3";
http.post(Uri.parse(phpEndPoint), body: {
"image": base64Image,
"name": fileName,
"cod_sat": widget.codigo,
"tipo": tipo,
}).then((res) async {
setState(() {
});
}).catchError((err) {
print(err);
});
}
My issue is that at line _upload(file); I am getting the error:
The argument type 'PlatformFile' can't be assigned to the parameter type 'File'
Is there a way to convert a PlatformFile generated by the package file_picker to the type File needed to upload the file?
PlatformFile has a path reference to the file, you can take that path and set a File object with that path like this:
final path = file.path
_upload(File(path));

Can't save video to Application directory - Flutter

I am working on an app where I want to record a video to file with the timestamp as name. As I understand it you should be able to use the returned XFile and use the saveTo function. I get an error that does seem odd to me.
Here is the code where I save the video:
void onStopRecordingButtonPressed() {
stopVideoRecording().then((video) async {
if (video != null) {
final path = await _localPath;
final file = File('$path/${timestamp() + ".mp4"}');
await file.create(recursive: true);
print("video path " + video.path.toString());
print("VideoFile: " + video.name.toString());
print("Desired path: " + file.toString());
var fileExists = await file.exists();
if (fileExists) {
print("fileExists");
} else {
print("No, this does not exist");
}
video.saveTo(file.toString());
}
});
}
Future<XFile?> stopVideoRecording() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isInitialized) {
return null;
}
try {
return cameraController.stopVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
}
and this is the output:
flutter: video path /var/mobile/Containers/Data/Application/3339192C-B309-4E08-8017-FFBD735CA576/Documents/camera/videos/REC_4525E32A-81C0-42BA-A3A4-48E325E44E58.mp4
flutter: VideoFile: REC_4525E32A-81C0-42BA-A3A4-48E325E44E58.mp4
flutter: Desired path: File: '/var/mobile/Containers/Data/Application/3339192C-B309-4E08-8017-FFBD735CA576/Documents/1652533015054.mp4'
flutter: fileExists <-- Exists
open on File: '/var/mobile/Containers/Data/Application/3339192C-B309-4E08-8017-FFBD735CA576/Documents/1652533015054.mp4': No such file or directory <-- So how can this be?
Application finished.
XFile.toString() is the string representation of the object, not a path.
File: '/var/mobile/Containers/Data/Application/3339192C-B309-4E08-8017-FFBD735CA576/Documents/1652533015054.mp4'
Try something like this:
video.saveTo(file.path);

FileSystemException: Cannot open file while trying to write new file

I'm trying to write file with custom name but getting error but if i used constant name it works just fine
here is my code
Future downloadFile(String url, String name) async {
//creating path
final tempDir =
(await AndroidExternalStorage.getExternalStoragePublicDirectory(
DirType.downloadDirectory));
//filename genearted from
customname = generated;
final file = File('$tempDir/myfolder/$customname');
try {
final response = await Dio().get(url,
onReceiveProgress: (count, total) {
setState(() {
isDownloading = true;
progress = ((count / total) * 100);
if (progress == 100) {
isDownloaded = true;
}
});
},
options:
Options(responseType: ResponseType.bytes, receiveTimeout: 0));
var raf = file.openSync(mode: FileMode.write);
raf.writeByteSync(response.data);
await raf.close();
} catch (e) {
log(e.toString());
}
}
error log
[log] FileSystemException: Cannot open file, path = '/storage/emulated/0/Download/myfolder/dunkin.zip' (OS Error: Permission denied, errno = 13)

Flutter and DIO: HandshakeException: Connection terminated during handshake

I'm using DIO for downloading images from network in my Flutter Application.
In general his is my code:
await Future.forEach(files, (file) async {
print(1);
entriesController.downloadIndex.value++;
if (file["video"] != null && file["video"].isNotEmpty) {
String videoPath = file["video"];
var appDocDir = await getTemporaryDirectory();
String savePath = appDocDir.path + "/$uniqueID.mp4";
await Dio().download(videoPath, savePath);
await ImageGallerySaver.saveFile(savePath);
}
if (file["video"] == null || file["video"].isEmpty) {
print(2);
String imagePath = file["image"];
print(3);
var appDocDir = await getTemporaryDirectory();
print(4);
String savePath = appDocDir.path + "/$uniqueID.jpg";
print(5);
try {
await Dio().download(imagePath, savePath);
} catch (e) {
print(e);
}
print(6);
await ImageGallerySaver.saveFile(savePath);
}
});
This is a loop which builds the network path to download the image and save them to the mobile gallery.
The problem: After maybe 50 downloaded images I get the following error on await Dio().download(imagePath, savePath); catch line:
flutter: DioError [DioErrorType.DEFAULT]: HandshakeException: Connection terminated during handshake
How can I solve this error? Is this maybe a timeout? By the way: The downloaded images are stored on DigitalOcean.

FileSystemException: Cannot copy file ' (OS Error: Is a directory, errno = 21)

I am trying to copy a sqflite database file from this path (getDatabasesPath()) to external storage,but I got this exception:
FileSystemException: Cannot copy file to '/storage/emulated/0/databaseBackup', path = '/data/user/0/com.example.project/databases/roznamcha.db' (OS Error: Is a directory, errno = 21)
My code:
Future<bool> _requestPermission(Permission permission) async {
if (await permission.isGranted) {
return true;
} else {
var result = await permission.request();
if (result == PermissionStatus.granted) {
return true;
}
}
return false;
}
Future<bool> createDirectory() async {
Directory directory;
try {
if (Platform.isAndroid) {
if (await _requestPermission(Permission.storage)) {
directory = await getExternalStorageDirectory();
String newPath = "";
print(directory);
List<String> paths = directory.path.split("/");
for (int x = 1; x < paths.length; x++) {
String folder = paths[x];
if (folder != "Android") {
newPath += "/" + folder;
} else {
break;
}
}
newPath = newPath + "/databaseBackup";
directory = Directory(newPath);
} else {
return false;
}
} else {
if (await _requestPermission(Permission.photos)) {
directory = await getTemporaryDirectory();
} else {
return false;
}
}
if (!await directory.exists()) {
await directory.create(recursive: true);
}
if (await directory.exists()) {
final pathdb = await getDatabasesPath();
// join database name and database path
final path = join(pathdb, 'roznamcha.db');
print('path ra print ko: $path');
File f = File(path);
var cop = await f.copy(directory.path);
print(directory.path);
print('copy file $cop');
}
} catch (e) {
print(e);
}
return false;
}
I added permission_handler package and also permission configuration to AndroidManiFaes.xml but I still get this error.