简体   繁体   中英

Flutter download a file from url automatically to downloads directory

Flutter 中是否有一种方法或软件包可以从直接 URL 将文件直接下载到 Android 和 iOS 的下载文件夹,例如:https://******/image.jpg,无需任何用户开销,只需单击一下和下载..

Yes use following packages to completely achieve it :

dio: ^4.0.0
path_provider: ^2.0.2
permission_handler: ^8.0.0+2

then use following code :

define variables:

late String _localPath;
late bool _permissionReady;
late TargetPlatform? platform;

get device platform in initState()

@override
  void initState() {
    super.initState();
    if (Platform.isAndroid) {
      platform = TargetPlatform.android;
    } else {
      platform = TargetPlatform.iOS;
    }
  }

for check and requesting device's permissions :

  Future<bool> _checkPermission() async {
    if (platform == TargetPlatform.android) {
      final status = await Permission.storage.status;
      if (status != PermissionStatus.granted) {
        final result = await Permission.storage.request();
        if (result == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

prepare for finding localpath :

Future<void> _prepareSaveDir() async {
    _localPath = (await _findLocalPath())!;

    print(_localPath);
    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
  }

  Future<String?> _findLocalPath() async {
    if (platform == TargetPlatform.android) {
      return "/sdcard/download/";
    } else {
      var directory = await getApplicationDocumentsDirectory();
      return directory.path + Platform.pathSeparator + 'Download';
    }
  }

and at last for downloading file:

InkWell(
        onTap: () async {
          _permissionReady = await _checkPermission();
          if (_permissionReady) {
            await _prepareSaveDir();
            print("Downloading");
            try {
              await Dio().download("https://******/image.jpg",
                  _localPath + "/" + "filename.jpg");
              print("Download Completed.");
            } catch (e) {
              print("Download Failed.\n\n" + e.toString());
            }
          }
        },
        child: Container(
          decoration: BoxDecoration(
              shape: BoxShape.circle, color: Colors.grey.withOpacity(0.5)),
          padding: EdgeInsets.all(8),
          child: Icon(Icons.download, color: Colors.black),
        ));

Make sure you have added required permissions in the AndroidManifest.xml :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

You can use Dio package to download any file.

A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.

Example

import 'package:dio/dio.dart';
var dio = Dio();
response = await dio.download('https://******/image.jpg');

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