Flutter download file in phone storage - flutter

I am not able to download file in the phone storage.. My code is..
Future<void> downloadFile() async {
Dio dio = Dio();
bool checkPermission1 =
await SimplePermissions.checkPermission(permission1);
print('checkPermission1');
print(checkPermission1);
if (checkPermission1 == false) {
await SimplePermissions.requestPermission(permission1);
checkPermission1 = await SimplePermissions.checkPermission(permission1);
}
if (checkPermission1 == true) {
String dirloc = "";
if (Platform.isAndroid) {
dirloc = "/sdcard/downloads/";
} else {
dirloc = (await getApplicationDocumentsDirectory()).path;
}
try {
FileUtils.mkdir([dirloc]);
await dio.download(url, dirloc + id + ".mp4",
onReceiveProgress: (receivedBytes, totalBytes) {
setState(() {
downloadingFlag = true;
progress =
((receivedBytes / totalBytes) * 100).toStringAsFixed(0) + "%";
});
});
} catch (e) {
print(e);
}
setState(() {
downloadingFlag = false;
downloadsFlag = false;
progress = "Download Completed.";
path = dirloc + id + ".mp4";
});
} else {
setState(() {
progress = "Permission Denied!";
});
}
}
I/flutter (23004): FileSystemException: Creation failed, path = '/sdcard/downloads' (OS Error: Permission denied, errno = 13)

Related

Save images in a custom folder in the gallery

Im new at Flutter and im trying to add images taken in my app to a custom folder in the gallery. Its the same as on WhatsApp, if you take a picture in a chat the WhatsApp create a custom folder called WhatsApp Images.
For that, I tried this:
Future<bool> saveFile(String url, String fileName) async {
Directory directory;
try {
if (Platform.isAndroid) {
if (await _requestPermission(Permission.storage)) {
directory = (await getExternalStorageDirectory())!;
String newPath = '';
List<String> folders = directory.path.split('/');
for (int x = 1; x < folders.length; x++) {
String folder = folders[x];
if (folder != 'Android') {
newPath += '/$folder';
} else {
break;
}
}
newPath = '$newPath/OnlaineApp';
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()) {
File saveFile = File('${directory.path}/$fileName');
await dio.download(url, saveFile.path,
onReceiveProgress: (downloaded, totalSize) {
setState(() {
progress = downloaded / totalSize;
});
});
if (Platform.isIOS) {
await ImageGallerySaver.saveFile(
saveFile.path,
isReturnPathOfIOS: true,
);
}
return true;
}
} catch (e) {
print(e);
}
return false;
}
Future<bool> _requestPermission(Permission permission) async {
if (await permission.isGranted) {
return true;
} else {
var result = await permission.request();
if (result == PermissionStatus.granted) {
return true;
} else {
return false;
}
}
}
downloadFile() async {
setState(() {
loading = true;
});
bool downloaded = await saveFile(
'lib/assets/images/fundo_interno.png',
'OnlaineApp Imagens',
);
if (downloaded) {
print('File downloaded');
} else {
print('Problem downloaded file');
}
setState(() {
loading = false;
});
}
I already add in Android>app>src>main> AndroidManifest.xml these lines of code (for permission):
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
...
android:requestLegacyExternalStorage="true"
The problem I got is: I/flutter ( 5424): FileSystemException: Creation failed, path = '/storage/emulated/0/OnlaineApp' (OS Error: Permission denied, errno = 13)

I try to write voice content to external file it work good but if I record for 1 minute or 20 seconds the size of file is 64 byte why

" i use flutte sound package "
"saveFile function get the path of file and the fileName and save it to external file "
Future<bool> saveFile(Uint8List url,String fileName) async {
Directory? directory;
directory = await getApplicationDocumentsDirectory();
/// print("direcory ===>"+directory.path.toString());
try {
if (Platform.isAndroid) {
directory = await getExternalStorageDirectory();
if (await _requstPermission(Permission.storage) &&
await _requstPermission(Permission.accessMediaLocation) &&
await _requstPermission(Permission.manageExternalStorage)) {
String newPath = "";
List<String> folders = directory!.path.split("/");
for (int i = 1; i < folders.length; i++) {
String folder = folders[i];
if (folder != "Android") {
newPath += "/" + folder;
} else {
break;
}
}
newPath = "/storage/emulated/0/Android/SpaChat2/";
directory = Directory(newPath);
//print(directory.path);
} else {
return false;
}
} else {
}
if (!await directory.exists()) {
await directory.create(recursive: true);
}
if (await directory.exists()) {
File audioFile = File(
directory.path +fileName.split("/").last);
print("//////////////////////////////////////////////");
// print(bytes);
print("url =============================================="+utf8.decode(url));
await audioFile.writeAsBytes(url);
return true;
}
} catch (e) {
print(e);
}
return false;
}
" _requstPermission get permission for access device resource "
Future<bool> _requstPermission(Permission permission) async {
if (await permission.isGranted) {
return true;
} else {
var res = await permission.request();
if (res == PermissionStatus.granted) {
return true;
} else {
return false;
}
}
}
" starting record voice"
void startRecord() async {
try {
_myRecorder.stopRecorder();
} catch (e) {}
currentDuration.value = Duration.zero;
try {
bool hasStorage = await _requstPermission(Permission.storage);
bool hasMic = await _requstPermission( Permission.microphone);
if (!hasStorage || !hasMic) {
if (!hasStorage) await _requstPermission(Permission.storage);
if (!hasMic) await _requstPermission( Permission.microphone);
print('[chat_composer] 🔴 Denied permissions');
return;
}
if (onRecordStart != null) onRecordStart!();
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path +
'/' +
DateTime.now().millisecondsSinceEpoch.toString() +
'.aac';
pathToSaveAudio=path;
await _myRecorder.startRecorder(
toFile: pathToSaveAudio,
//codec: Codec.aacADTS,
);
emit(RecordAudioStarted());
} catch (e) {
emit(RecordAudioReady());
}
}
" stopRecord functon stop recording after stop record voice it call saveFile function and add the path of voice to saveFile arguments "
void stopRecord() async {
// timer.cancel();
try {
String? result = await _myRecorder.stopRecorder();
if (result != null) {
// tempPath =result;
print('[chat_composer] 🟢 Audio path: "$result');
onRecordEnd(result);
Uint8List bytes = Utf8Encoder().convert(pathToSaveAudio);
saveFile(bytes,pathToSaveAudio);
}
} finally {
currentDuration.value = Duration.zero;
}
emit(RecordAudioReady());
}

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.

Cannot save a file to the documents directory IOS Flutter

I tried to test the file download and saving to the documents directory. The code works on Android, but fails on IOS. Here is the code:
var dir = await getApplicationDocumentsDirectory();
var documentName = "";
documentName = "testname.pdf";
var storePath = "${dir.path}/$documentName";
var errorOccurred = false;
try {
await dio.download(url, storePath, onReceiveProgress: (rec, total) {
print("Rec: $rec , Total: $total");
_setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
});
} catch (e) {
print(e);
}
The error is the following:
Exception: PlatformException(file_not_found, File not found: '/../Devices/3D122270-E919-455D-AF3F-F048EC32CBB7/data/Containers/Data/Application/1262A294-59DC-47A5-B5A6-24FBAD9D53CA/Library/Caches/testname.pdf', null, null)
I am testing on simulator

How to fetch filename from url [Flutter][Dio]

This is My code snippet instead of mypdf.pdf i want to get filename from the url like in android app development,since I'm new in flutter i have no idea can anyone help me
Future<void> downloadPDF() async {
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
await dio.download(pdfurl, "${dir.path}/mypdf.pdf",
onProgress: (rec, total) {
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
});
} catch (e) {
print(e);
}
setState(() {
downloading = false;
progressString = "Completed";
});
print("Download completed");
}
did you try it ?
File file = new File("/dir1/dir2/file.ext");
String basename = basename(file.path);
# file.ext
for more details https://flutter.dev/docs/cookbook/persistence/reading-writing-files
You can use the built-in substring and lastIndexOf methods:
final url = "http://africau.edu/images/default/sample.pdf";
final filename = url.substring(url.lastIndexOf("/") + 1);