简体   繁体   English

如何在flutter中将https网络URL图像下载到应用程序目录中

[英]how to download https network URL images into app directory in flutter

import 'package:http/http.dart' as http;将 'package:http/http.dart' 导入为 http;

import 'package:image_picker_saver/image_picker_saver.dart';导入'包: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);
}

It looks similar to this: How to Download Video from Online and store it local Device then play video on Flutter apps Using video player?它看起来类似于: 如何从在线下载视频并将其存储到本地设备,然后使用视频播放器在 Flutter 应用程序上播放视频?

Here's the answer I've given at the time:这是我当时给出的答案:

You might wanna give a try to the dio package it is an http client that supports file downloading and save it locally to a given path.您可能想尝试一下dio包,它是一个 http 客户端,支持文件下载并将其本地保存到给定路径。

Here's a code sample (source: iampawan's Github )这是一个代码示例(来源: 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");
}

You will also need path_provider tu use getApplicationDocumentsDirectory() .您还需要path_provider tu 使用getApplicationDocumentsDirectory()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM