I built an app to upload attachments to Firebase Storage, with the URL saved in Firestore. The upload part works nicely. I also added a download button for downloading the relevant attachment. When clicking the download button, the app should split the last ‘.’ to identify the file type and download the relevant file path. However, unfortunately, when clicking the download button, an error occurs.
UI screenshot
A example for the file firestore url
https://firebasestorage.googleapis.com/v0/b/petpulz-93d6f.appspot.com/o/records%2F49785b2d-5bc2-47c1-9ac2-2654627851de3518522212366212285.jpg?alt=media&token=4690a174-c094-4019-a540-17ca8437a69e.jpg
My code
IconButton(
icon: Icon(Icons.download),
onPressed: () async {
// Get the file from _selectedFiles
final file = _selectedFiles[index];
// Open the download dialog
final directory = await getExternalStorageDirectory();
final savePath = path.join(directory!.path, 'Download', file.path.split('/').last);
await showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Download'),
content: Text('Do you want to download ${file.path.split('/').last}'),
actions: [
TextButton(
child: Text('Cancel'),
onPressed: () => Navigator.pop(context),
),
TextButton(
child: Text('Download'),
onPressed: () async {
// Download the file
await http.get(Uri.parse(file.path)).then((response) async {
final bytes = response.bodyBytes;
await File(savePath).writeAsBytes(bytes);
});
// Close the dialog
Navigator.pop(context);
// Show a message to indicate that the download is complete
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Download complete')),
);
},
),
],
),
);
},
),
path provider package
path_provider: ^2.0.2
how to solve this error ?
2
Answers
I solved the error and now file download working for android and ios prefectly.
and for the ios path you should import
for that import you need to install relevant package
path_provider: ^2.0.2
and also specially you need to give permisions in the AndroidManifest.xml file in android and info.plist file in ios folder
info.plist(ios) add these code line
simply these permissions are for the documents .
AndroidManifest.xml(android) add these permission code lines
On Android, the downloaded files should be saved to the download folder, and on iOS, they should be saved to the Files app in a separate folder created using the application name.
I should clarify that with this code, any file type can be downloaded to the device, not just PDF files and images.
change directory because an above android 10 version devices not access to use /storage/emulated/0/Android/data directory