|
|
@@ -0,0 +1,53 @@ |
|
|
|
import 'dart:collection'; |
|
|
|
|
|
|
|
import 'package:dio/dio.dart'; |
|
|
|
import 'package:flutter/material.dart'; |
|
|
|
import 'package:fluttertoast/fluttertoast.dart'; |
|
|
|
import 'package:image_gallery_saver/image_gallery_saver.dart'; |
|
|
|
import 'package:path_provider/path_provider.dart'; |
|
|
|
import 'package:permission_handler/permission_handler.dart'; |
|
|
|
|
|
|
|
class Download { |
|
|
|
static HashMap hashMap = HashMap(); |
|
|
|
|
|
|
|
Future<String> fileToGallery( |
|
|
|
String url, { |
|
|
|
String postfix, |
|
|
|
Function(int, int) progress, |
|
|
|
}) async { |
|
|
|
// 检查是否已有读写内存的权限 |
|
|
|
bool status = await Permission.storage.isGranted; |
|
|
|
|
|
|
|
//判断如果还没拥有读写权限就申请获取权限 |
|
|
|
if (status || await Permission.storage.request().isGranted) { |
|
|
|
if (hashMap.containsKey(url)) { |
|
|
|
return "正在下载"; |
|
|
|
} else { |
|
|
|
hashMap[url] = false; |
|
|
|
} |
|
|
|
try { |
|
|
|
var strs = url.split('.'); |
|
|
|
if (strs.length < 0) { |
|
|
|
return "文件链接错误"; |
|
|
|
} |
|
|
|
var appDocDir = await getTemporaryDirectory(); |
|
|
|
String savePath = appDocDir.path + "/" + DateTime.now().toIso8601String().toString() + (strs[strs.length - 1].length > 4 ? (postfix ?? "") : strs[strs.length - 1]); |
|
|
|
await Dio().download(url, savePath, onReceiveProgress: (count, toal) { |
|
|
|
if(progress!=null){ |
|
|
|
progress(count, toal); |
|
|
|
} |
|
|
|
}); |
|
|
|
print(savePath); |
|
|
|
final result = await ImageGallerySaver.saveFile(savePath); |
|
|
|
print(result); |
|
|
|
return "保存成功"; |
|
|
|
} catch (e) { |
|
|
|
return "下载失败,原因:" + e.toString(); |
|
|
|
} finally { |
|
|
|
hashMap.remove(url); |
|
|
|
} |
|
|
|
} else { |
|
|
|
return "请前往系统设置开启应用的内存读取权限再尝试"; |
|
|
|
} |
|
|
|
} |
|
|
|
} |