简体   繁体   中英

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

import 'package:http/http.dart' as http;

import 'package: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?

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.

Here's a code sample (source: iampawan's 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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