I have a base64 encoded string of a PDF file. I'm trying to save it as a file in the android device. My code runs with no error, but i can't find the file.
Uint8List bytes = base64.decode(encodedStr);
String dir = (await getExternalStorageDirectories(
type: StorageDirectory.downloads))!
.first
.path;
File file = File("$dir/"
DateTime.now().millisecondsSinceEpoch.toString()
".pdf");
await file.writeAsBytes(bytes);
Also, I tried to include code to ask for permission before trying to save the file, but it didn't change anything.
var status = await Permission.storage.status;
if (!status.isGranted) {
await Permission.storage.request();
}
if (await Permission.storage.request().isGranted) {
try {
await file.writeAsBytes(bytes);
} catch (e) {
print(e);
}
}
And, as another attempt, I included these permission on my AndroidManifest file. Also, no changes.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
//dir = /storage/emulated/0/Android/data/com.xxxxxxxxxxxxxxxx.xxxxx/files/Download
//dir file = /storage/emulated/0/Android/data/com.xxxxxxxxxxxxxxxx.xxxxx/files/Download/1655924904315.pdf
//file path after written = /storage/emulated/0/Android/data/com.xxxxxxxxxxxxxxxx.xxxxx/files/Download/1655924904315.pdf
Is there anything wrong with my code or something that I can change in order for it to work ?
The above code is using path_provider and permission_handler packages and was tested in an emulator and in a physical device.
Thanks.
CodePudding user response:
Try importing io and use file of io and use this package https://pub.dev/packages/pdf
import 'dart:io' as io;
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
final pdf = pw.Document();
final dir = await getTemporaryDirectory();
final path = "${dir.path}/pdfname.pdf";
final file = await io.File(path).writeAsBytes(pdf.save());
CodePudding user response:
It happens that the files are being correctly generated, but they are being saved in the application's directory. A download folder has being created and the files are being saved there. I didn't find the files searching via android, but when I connected my physical device to a PC I was able the find them.
It seems that this has something to do with this https://github.com/flutter/flutter/issues/35783 . Path_provider started to return application document directory after 1.1.0 instead of the general downloads folder.
I'll check how to access the path I want correctly.