首页 > 解决方案 > 如何在flutter中将https网络URL图像下载到应用程序目录中

问题描述

将“包:http/http.dart”导入为 http;

导入“包:image_picker_saver/image_picker_saver.dart”;

try {
  var response = await http.get(imageURL); // problem is here (only working on http URL)

  debugPrint(response.statusCode.toString());

  var filePath = await ImagePickerSaver.saveFile(
      fileData: response.bodyBytes);

  var savedFile= File.fromUri(Uri.file(filePath));

  print('Image path: $savedFile');

 /* setState(() {
    _imageFile = Future<File>.sync(() => savedFile);
  });*/

} on PlatformException catch (error) {
  print(error);
}

标签: flutterhttpsdart-pub

解决方案


它看起来类似于:How to Download Video from Online and store it local Device then play video on Flutter apps Using video player?

这是我当时给出的答案:

您可能想尝试一下dio包,它是一个支持文件下载并将其本地保存到给定路径的 http 客户端。

这是一个代码示例(来源:iampawan 的 Github

Future downloadFile(String url) async {
  Dio dio = Dio();

  try {
    var dir = await getApplicationDocumentsDirectory();
    await dio.download(url, "${dir.path}/myFile.txt", onProgress: (rec, total) {
      print("Rec: $rec , Total: $total");
    });
  } catch (e) {
    print(e);
  }
  print("Download completed");
}

您还需要使用path_providergetApplicationDocumentsDirectory()


推荐阅读