gpt4 book ai didi

Flutter 自动从 url 下载文件到下载目录

转载 作者:行者123 更新时间:2023-12-05 01:04:13 25 4
gpt4 key购买 nike

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

最佳答案

是的,使用以下软件包来完全实现它:

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

然后使用以下代码:

定义变量:

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

initState() 中获取设备平台

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

用于检查和请求设备的权限:

  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;
}

准备寻找本地路径:

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';
}
}

最后是下载文件:

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),
));

确保您已在 AndroidManifest.xml 中添加所需的权限:

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

关于Flutter 自动从 url 下载文件到下载目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72530115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com