Created
April 13, 2018 22:14
-
-
Save slightfoot/6f502205aca15e3cbf461df879673b56 to your computer and use it in GitHub Desktop.
Download file in Dart/Flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static var httpClient = new HttpClient(); | |
Future<File> _downloadFile(String url, String filename) async { | |
var request = await httpClient.getUrl(Uri.parse(url)); | |
var response = await request.close(); | |
var bytes = await consolidateHttpClientResponseBytes(response); | |
String dir = (await getApplicationDocumentsDirectory()).path; | |
File file = new File('$dir/$filename'); | |
await file.writeAsBytes(bytes); | |
return file; | |
} |
Hello, I've created a plugin for this long time ago, file_saver
Future saveLocalFile(BuildContext context, String localFilePath) async {
try {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return Center(
child: CircularProgressIndicator(),
);
},
);
String filePath = localFilePath;
File file = File(filePath);
if (await file.exists()) {
Directory? appDocDir = await getExternalStorageDirectory();
if (appDocDir != null) {
String destPath = "${appDocDir.path}/${file.path.split('/').last}";
await file.copy(destPath);
String mimeType = _getMimeType(destPath);
if (Platform.isAndroid) {
final androidFile = File(destPath);
await androidFile.writeAsBytes(await file.readAsBytes(),
flush: true);
await androidFile.uri;
}
Navigator.pop(context);
showMessage('File saved successfully', Colors.green);
} else {
throw 'Failed to get directory for saving file';
}
} else {
throw 'File not found at path: $filePath';
}
} catch (e) {
Navigator.pop(context);
showMessage('Failed to save file: $e', Colors.red);
}
}
file downloading but not opening , please give me a solution
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found a way to download files in Flutter Web using
html.AnchorElement()
.I hope this sample code would be helpful :)
sample code is downloading file from Firebase Storage