基础库
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

download.dart 1.9 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import 'dart:collection';
  2. import 'dart:io';
  3. import 'package:dio/dio.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:fluttertoast/fluttertoast.dart';
  6. import 'package:path_provider/path_provider.dart';
  7. import 'package:permission_handler/permission_handler.dart';
  8. import 'package:save_image/save_image.dart';
  9. class Download {
  10. static HashMap hashMap = HashMap();
  11. Future<String> fileToGallery(
  12. String url, {
  13. String postfix,
  14. Function(int, int) progress,
  15. }) async {
  16. // 检查是否已有读写内存的权限
  17. bool status = await Permission.storage.isGranted;
  18. //判断如果还没拥有读写权限就申请获取权限
  19. if (status || await Permission.storage.request().isGranted) {
  20. if (hashMap.containsKey(url)) {
  21. return "正在下载";
  22. } else {
  23. hashMap[url] = false;
  24. }
  25. try {
  26. var strs = url.split('.');
  27. if (strs.length < 0) {
  28. return "文件链接错误";
  29. }
  30. var appDocDir = await getTemporaryDirectory();
  31. String savePath = appDocDir.path +
  32. "/" +
  33. DateTime.now().toIso8601String().toString() +
  34. (strs[strs.length - 1].length > 4 ? (postfix ?? "") : ('.' + strs[strs.length - 1]));
  35. await Dio().download(url, savePath, onReceiveProgress: (count, toal) {
  36. if (progress != null) {
  37. progress(count, toal);
  38. }
  39. });
  40. print(savePath);
  41. var result = await SaveImage.save(imageBytes: File(savePath).readAsBytesSync());
  42. if (result != null && result) {
  43. return "保存成功";
  44. } else {
  45. return "保存失败";
  46. }
  47. } catch (e) {
  48. return "下载失败,原因:" + e.toString();
  49. } finally {
  50. hashMap.remove(url);
  51. }
  52. } else {
  53. return "请前往系统设置开启应用的内存读取权限再尝试";
  54. }
  55. }
  56. }