当前位置:   article > 正文

flutter 文件上传组件和大文件分片上传

flutter 文件上传组件和大文件分片上传

文件分片上传

资料

https://www.cnblogs.com/caijinglong/p/11558389.html

使用分段上传来上传和复制对象 - Amazon Simple Storage Service

因为公司使用的是亚马逊的s3桶  下面是查阅资料获得的

亚马逊s3桶的文件上传分片

分段上分为三个步骤:开始上传、上传对象分段,以及在上传所有分段后完成分段上传。在收到完成分段上传请求后,Amazon S3 会利用上传的分段创建对象,然后您可以像在您的存储桶中访问任何其他对象一样访问该对象。

您可以列出所有正在执行的分段上传,或者获取为特定分段上传操作上传的分段列表。以上每个操作都在本节中进行了说明。

分段上传开始

当您发送请求以开始分段上传时,Amazon S3 将返回具有上传 ID 的响应,此 ID 是分段上传的唯一标识符。无论您何时上传分段、列出分段、完成上传或停止上传,您都必须包括此上传 ID。如果您想要提供描述已上传的对象的任何元数据,必须在请求中提供它以开始分段上传。

分段上传

上传分段时,除了指定上传 ID,还必须指定分段编号。您可以选择 1 和 10000 之间的任意分段编号。分段编号在您正在上传的对象中唯一地识别分段及其位置。您选择的分段编号不必是连续序列(例如,它可以是 1、5 和 14)。如果您使用之前上传的分段的同一分段编号上传新分段,则之前上传的分段将被覆盖。

无论您何时上传分段,Amazon S3 都将在其响应中返回实体标签 (ETag) 标头。对于每个分段上传,您必须记录分段编号和 ETag 值。所有对象分段上传的 ETag 值将保持不变,但将为每个分段分配不同的分段号。您必须在随后的请求中包括这些值以完成分段上传。

分段上传完成

完成分段上传时,Amazon S3 通过按升序的分段编号规范化分段来创建对象。如果在开始分段上传请求中提供了任何对象元数据,则 Amazon S3 会将该元数据与对象相关联。成功完成请求后,分段将不再存在。

完成分段上传请求必须包括上传 ID 以及分段编号和相应的 ETag 值的列表。Amazon S3 响应包括可唯一地识别组合对象数据的 ETag。此 ETag 无需成为对象数据的 MD5 哈希。

文件分片基本原理

前端使用插件获取到本地选择的文件,判断文件的大小,超过设置的限制数,就进行大文件分片上传逻辑

第一步

进行文件分片 下面这个方法 返回的是大文件分片后的开始索引和结束索引

  1. List<List<int>> sliceFileIntoChunks(
  2. int fileSize, int sliceMinSize, int sliceMaxCount) {
  3. List<List<int>> slices = [];
  4. int start = 0;
  5. while (start < fileSize) {
  6. int end = start + sliceMinSize;
  7. if (end > fileSize || slices.length + 1 >= sliceMaxCount) {
  8. end = fileSize;
  9. }
  10. slices.add([start, end]);
  11. start = end;
  12. }
  13. return slices;
  14. }

第二步

将分片信息 生成新的配置对象 配置对象会导出 分片的json

List<SliceChunkItem> config = await utils.getJsonFromSplitFileIntoChunks();
  1. // 切片项
  2. class SliceChunkItem {
  3. // 切片所在文件的位置
  4. final int start;
  5. final int end;
  6. final int partNumber;
  7. String uploadId = "";
  8. String tag = "";
  9. String checksum = "";
  10. List<int> fileBytes = [];
  11. MultipartFile? multipartFile;
  12. SliceChunkItem({
  13. required this.start,
  14. required this.end,
  15. required this.partNumber,
  16. });
  17. setUploadId(id) {
  18. uploadId = id;
  19. }
  20. setTag(id) {
  21. tag = id;
  22. }
  23. Map<String, dynamic> toJson() {
  24. return {
  25. "partNumber": partNumber,
  26. "tag": tag,
  27. "checksum": checksum,
  28. };
  29. }
  30. List<int> toClunk() {
  31. return fileBytes;
  32. }
  33. }

第三步

接口发送,分为三个接口,第一个为初始化接口、第二个为分片上传接口、第三个为文件合成接口(因为需求原因 希望存的是一个完整的文件,且不做分片下载功能)

第一个接口 传递了文件名 和加密的类型 因为是亚马逊 hashMethod= SHA1

String fileName = file.path.split('/').last;
  1. final aa = await multipartUploadInit(
  2. fileName: fileName, checksumType: FileUtils.hashMethod);

第二个接口 因为需要并发去发分片 

分片使用FormData进行存 其他信息也加在FormData中

  1. static multipartUpload({
  2. required FormData formData,
  3. }) async {
  4. final res = await dio.post(
  5. Url.multipartUpload,
  6. data: formData,
  7. options: Options(
  8. method: "post",
  9. contentType: "multipart/form-data",
  10. sendTimeout: const Duration(days: 5),
  11. receiveTimeout: const Duration(days: 5),
  12. ),
  13. );
  14. return res.data;
  15. }
  1. // 同时对分片进行并发
  2. Future sendItems({
  3. required List<SliceChunkItem> config,
  4. required int concurrentLimit,
  5. required Function(SliceChunkItem) callback,
  6. }) async {
  7. return await Future.wait(config.map((item) async {
  8. // 判断是否需要取消请求
  9. if (cancelCompleter.isCompleted) {
  10. throw 'Requests are cancelled';
  11. }
  12. // 控制并发数量
  13. while (count >= concurrentLimit) {
  14. await Future.delayed(const Duration(milliseconds: 100));
  15. }
  16. count++;
  17. try {
  18. await callback(item);
  19. } finally {
  20. count--;
  21. }
  22. }));
  23. }

使用

  1. await utils.sendItems(
  2. config: config,
  3. concurrentLimit: 5,
  4. callback: (item) async {
  5. item.setUploadId(uploadId);
  6. "[分片上传] bb 开始上传 partNumber ${item.partNumber} ".w();
  7. var fileBytes = await utils.getRange(item.start, item.end);
  8. item.checksum = utils.calculateSHA1FormList(fileBytes);
  9. // 直接传递数组fileBytes 给dio 会导致内存崩溃
  10. formData = FormData.fromMap({
  11. 'file': MultipartFile.fromBytes(fileBytes, filename: "11"),
  12. 'partNumber': item.partNumber,
  13. 'checksum': item.checksum,
  14. 'uploadId': item.uploadId,
  15. });
  16. final b = await multipartUpload(formData: formData);
  17. finalUploadSliceCount++;
  18. onSendProgress?.call(finalUploadSliceCount, config.length);
  19. "[分片上传] bb 结束上传 partNumber ${item.partNumber} $b".w();
  20. String tag = b["data"]["tag"];
  21. item.setTag(tag);
  22. });

第三个接口

  1. final cc = await multipartUploadComplete(
  2. // checksum: checksum,
  3. uploadId: uploadId,
  4. partList: config.map((e) => e.toJson()).toList(),
  5. );

大文件加载到内存问题

1、读大文件的时候

去拿文件的句柄 然后通过移动获取不同的文件段

file.openRead();

2、读取后存储问题

如果将获取的分片数据直接存到一个类里面,这样的操作会导致内存被撑爆,

必须发送接口的时候再进行 文件指针方式进行文件数据读取 然后发送接口后直接释放

所有分片上传的接口 做了 读取大文件分片数据的逻辑操作

3、对大文件分片 进行哈希计算

错误代码示范

  1. // ShA 1 进行文件哈希
  2. Future<String> calculateSHA1() async {
  3. if (await file.exists()) {
  4. List<int> contents = await file.readAsBytes();
  5. Digest sha1Result = sha1.convert(contents);
  6. return sha1Result.toString();
  7. } else {
  8. throw const FileSystemException('File not found');
  9. }
  10. }

修改后的代码 (对内存基本没影响)

  1. Future<String> calculateSHA1() async {
  2. if (await file.exists()) {
  3. Digest value = await sha1.bind(file.openRead()).first;
  4. return value.toString();
  5. } else {
  6. throw const FileSystemException('File not found');
  7. }
  8. }

出现的问题 (就是内存被撑爆的原因)

E/DartVM (24105): Exhausted heap space, trying to allocate 67108872 bytes. E/flutter (24105): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Out of Memory

出现问题的地方 (分片完成后 直接加载每个分片到内存中了 所有导致内容崩溃)

如下面代码 将获得的分片数据 存在了内存中 ,如果文件过大 就会被撑爆

  1. Future<List<SliceChunkItem>> getJsonFromSplitFileIntoChunks() async {
  2. List<SliceChunkItem> sliceChunkList = [];
  3. // int i = 0;
  4. int partNumber = 1;
  5. // List<int> chunks = splitFileIntoChunks();
  6. // for (var v in chunks) {
  7. // sliceChunkList.add(
  8. // SliceChunkItem(
  9. // start: i,
  10. // end: v + i,
  11. // fileBytes: await getRange(i, v + i),
  12. // partNumber: partNumber,
  13. // ),
  14. // );
  15. // i = v;
  16. // partNumber++;
  17. // }
  18. List<List<int>> chunks =
  19. sliceFileIntoChunks(file.lengthSync(), sliceMinSize, sliceMaxCount);
  20. "[分片上传] ${chunks.length}".w();
  21. for (List<int> v in chunks) {
  22. sliceChunkList.add(
  23. SliceChunkItem(
  24. start: v[0],
  25. end: v[1],
  26. fileBytes: await getRange(v[0], v[1]),
  27. partNumber: partNumber,
  28. ),
  29. );
  30. partNumber++;
  31. }
  32. return sliceChunkList;
  33. }

修改如下

发送的时候 再去进行获取 fileBytes 和 checksum;

完整代码如下

大文件上传工具类

  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:LS/common/extension/custom_ext.dart';
  5. import 'package:crypto/crypto.dart';
  6. import 'package:dio/dio.dart';
  7. class MyCompleter<T> {
  8. MyCompleter();
  9. Completer<T> completer = Completer();
  10. Future<T> get future => completer.future;
  11. void reply(T result) {
  12. if (!completer.isCompleted) {
  13. completer.complete(result);
  14. }
  15. }
  16. }
  17. class FileUtils {
  18. File file;
  19. // 文件哈希
  20. String hash = "";
  21. static String hashMethod = "SHA1";
  22. // 每个切片最小的大小
  23. int sliceMinSize = 1024 * 1024 * 10; // 10MB
  24. // 最大的切片数量
  25. int sliceMaxCount = 10000;
  26. // 限制并发数量的计数器
  27. int count = 0;
  28. // 用于取消请求的Completer
  29. final cancelCompleter = Completer<void>();
  30. FileUtils(this.file) {
  31. // 后端改动不需要l
  32. // // 默认后台进行文件求哈希
  33. // backstageCalculateSHA1();
  34. }
  35. // 读取文件的某个范围返回
  36. Future<List<int>> getRange(int start, int end) async {
  37. if (start < 0) {
  38. throw RangeError.range(start, 0, file.lengthSync());
  39. }
  40. if (end > file.lengthSync()) {
  41. throw RangeError.range(end, 0, file.lengthSync());
  42. }
  43. final c = MyCompleter<List<int>>();
  44. List<int> result = [];
  45. file.openRead(start, end).listen((data) {
  46. result.addAll(data);
  47. }).onDone(() {
  48. c.reply(result);
  49. });
  50. return c.future;
  51. }
  52. Stream<List<int>> getRangeStream(int start, int end) {
  53. if (start < 0) {
  54. throw RangeError.range(start, 0, file.lengthSync());
  55. }
  56. if (end > file.lengthSync()) {
  57. throw RangeError.range(end, 0, file.lengthSync());
  58. }
  59. return file.openRead(start, end);
  60. }
  61. // 读取文件的前n个字节返回
  62. List<int> splitFileIntoChunks() {
  63. final size = file.lengthSync();
  64. int chunkSize = size ~/ sliceMaxCount;
  65. chunkSize = chunkSize < sliceMinSize ? sliceMinSize : chunkSize;
  66. List<int> chunkSizes = [];
  67. int currentPosition = 0;
  68. while (currentPosition < size) {
  69. int remainingSize = size - currentPosition;
  70. int currentChunkSize =
  71. remainingSize > chunkSize ? chunkSize : remainingSize;
  72. chunkSizes.add(currentChunkSize);
  73. currentPosition += currentChunkSize;
  74. }
  75. return chunkSizes;
  76. }
  77. List<List<int>> sliceFileIntoChunks(
  78. int fileSize, int sliceMinSize, int sliceMaxCount) {
  79. List<List<int>> slices = [];
  80. int start = 0;
  81. while (start < fileSize) {
  82. int end = start + sliceMinSize;
  83. if (end > fileSize || slices.length + 1 >= sliceMaxCount) {
  84. end = fileSize;
  85. }
  86. slices.add([start, end]);
  87. start = end;
  88. }
  89. return slices;
  90. }
  91. Future<List<SliceChunkItem>> getJsonFromSplitFileIntoChunks() async {
  92. List<SliceChunkItem> sliceChunkList = [];
  93. int partNumber = 1;
  94. List<List<int>> chunks =
  95. sliceFileIntoChunks(file.lengthSync(), sliceMinSize, sliceMaxCount);
  96. "[分片上传] 当前分片 ${chunks.length}".w();
  97. for (List<int> v in chunks) {
  98. sliceChunkList.add(
  99. SliceChunkItem(
  100. start: v[0],
  101. end: v[1],
  102. partNumber: partNumber,
  103. ),
  104. );
  105. partNumber++;
  106. }
  107. return sliceChunkList;
  108. }
  109. // 将M 单位转为基本单位字节
  110. static int mToSize(int m) {
  111. return 1024 * 1024 * m;
  112. }
  113. // ShA 1 进行文件哈希
  114. Future<String> calculateSHA1(Stream<List<int>> stream) async {
  115. Digest digest = await sha1.bind(stream).first;
  116. return base64.encode(digest.bytes);
  117. }
  118. // 将数组数据重新组合成文件
  119. ///
  120. /// 测试使用 将分片合成一个文件 写到本地
  121. // String appDocDir = (await getDownloadsDirectory())?.path ?? "";
  122. // String filePath = '$appDocDir/new.zip';
  123. // await FileUtils.mergeChunksIntoFile(
  124. // config.map((e) => e.toClunk()).toList(), filePath);
  125. static Future<void> mergeChunksIntoFile(
  126. List<List<int>> chunks, String outputPath) async {
  127. File outputFile = File(outputPath);
  128. outputFile.createSync();
  129. IOSink output = outputFile.openWrite(mode: FileMode.writeOnlyAppend);
  130. "将数组数据重新组合成文件 a".w();
  131. for (List<int> chunk in chunks) {
  132. output.add(chunk);
  133. "将数组数据重新组合成文件 b".w();
  134. }
  135. "将数组数据重新组合成文件 c".w();
  136. await output.close();
  137. }
  138. String calculateSHA1FormList(List<int> data) {
  139. Digest digest = sha1.convert(data);
  140. return base64.encode(digest.bytes);
  141. }
  142. static String staticCalculateSHA1FormList(List<int> data) {
  143. Digest digest = sha1.convert(data);
  144. return base64.encode(digest.bytes);
  145. }
  146. // 后台进行对文件的哈希
  147. // backstageCalculateSHA1() async {
  148. // hash = await calculateSHA1();
  149. // return hash;
  150. // }
  151. // 同时对分片进行并发
  152. Future sendItems({
  153. required List<SliceChunkItem> config,
  154. required int concurrentLimit,
  155. required Function(SliceChunkItem) callback,
  156. }) async {
  157. return await Future.wait(config.map((item) async {
  158. // 判断是否需要取消请求
  159. if (cancelCompleter.isCompleted) {
  160. throw 'Requests are cancelled';
  161. }
  162. // 控制并发数量
  163. while (count >= concurrentLimit) {
  164. await Future.delayed(const Duration(milliseconds: 100));
  165. }
  166. count++;
  167. try {
  168. await callback(item);
  169. } finally {
  170. count--;
  171. }
  172. }));
  173. }
  174. // 取消所有请求
  175. cancelSendItems() {
  176. if (!cancelCompleter.isCompleted) {
  177. cancelCompleter.complete();
  178. }
  179. count = 0;
  180. "[切片上传] 取消并发成功".w();
  181. }
  182. }
  183. // 切片项
  184. class SliceChunkItem {
  185. // 切片所在文件的位置
  186. final int start;
  187. final int end;
  188. final int partNumber;
  189. String uploadId = "";
  190. String tag = "";
  191. String checksum = "";
  192. List<int> fileBytes = [];
  193. MultipartFile? multipartFile;
  194. SliceChunkItem({
  195. required this.start,
  196. required this.end,
  197. required this.partNumber,
  198. });
  199. setUploadId(id) {
  200. uploadId = id;
  201. }
  202. setTag(id) {
  203. tag = id;
  204. }
  205. Map<String, dynamic> toJson() {
  206. return {
  207. "partNumber": partNumber,
  208. "tag": tag,
  209. "checksum": checksum,
  210. };
  211. }
  212. List<int> toClunk() {
  213. return fileBytes;
  214. }
  215. }

分片上传总接口

  1. // 文件分片上传
  2. static uploadSliceFile(
  3. String path, {
  4. ProgressCallback? onSendProgress,
  5. required Function(FileUtils) getFileUtils,
  6. }) async {
  7. File file = File(path);
  8. String fileName = file.path.split('/').last;
  9. final utils = FileUtils(file);
  10. getFileUtils.call(utils);
  11. List<SliceChunkItem> config = await utils.getJsonFromSplitFileIntoChunks();
  12. final aa = await multipartUploadInit(
  13. fileName: fileName, checksumType: FileUtils.hashMethod);
  14. String uploadId = aa['data']['uploadId'];
  15. "[分片上传] aa $aa".w();
  16. int finalUploadSliceCount = 0;
  17. FormData formData;
  18. // for (SliceChunkItem item in config) {
  19. // item.setUploadId(uploadId);
  20. // "[分片上传] bb 开始上传 partNumber ${item.partNumber} ".w();
  21. // var fileBytes = await utils.getRange(item.start, item.end);
  22. // item.checksum = utils.calculateSHA1FormList(fileBytes);
  23. // // 直接传递数组fileBytes 给dio 会导致内存崩溃
  24. // formData = FormData.fromMap({
  25. // 'file': MultipartFile.fromBytes(fileBytes, filename: "11"),
  26. // 'partNumber': item.partNumber,
  27. // 'checksum': item.checksum,
  28. // 'uploadId': item.uploadId,
  29. // });
  30. // final b = await multipartUpload(formData: formData);
  31. // finalUploadSliceCount++;
  32. // onSendProgress?.call(finalUploadSliceCount, config.length);
  33. // "[分片上传] bb 结束上传 partNumber ${item.partNumber} $b".w();
  34. // String tag = b["data"]["tag"];
  35. // item.setTag(tag);
  36. // }
  37. await utils.sendItems(
  38. config: config,
  39. concurrentLimit: 5,
  40. callback: (item) async {
  41. item.setUploadId(uploadId);
  42. "[分片上传] bb 开始上传 partNumber ${item.partNumber} ".w();
  43. var fileBytes = await utils.getRange(item.start, item.end);
  44. item.checksum = utils.calculateSHA1FormList(fileBytes);
  45. // 直接传递数组fileBytes 给dio 会导致内存崩溃
  46. formData = FormData.fromMap({
  47. 'file': MultipartFile.fromBytes(fileBytes, filename: "11"),
  48. 'partNumber': item.partNumber,
  49. 'checksum': item.checksum,
  50. 'uploadId': item.uploadId,
  51. });
  52. final b = await multipartUpload(formData: formData);
  53. finalUploadSliceCount++;
  54. onSendProgress?.call(finalUploadSliceCount, config.length);
  55. "[分片上传] bb 结束上传 partNumber ${item.partNumber} $b".w();
  56. String tag = b["data"]["tag"];
  57. item.setTag(tag);
  58. });
  59. // 废弃 后端不需要整体文件的hash
  60. // String checksum = utils.hash;
  61. // if (checksum.isEmpty) {
  62. // checksum = await utils.backstageCalculateSHA1();
  63. // }
  64. final cc = await multipartUploadComplete(
  65. // checksum: checksum,
  66. uploadId: uploadId,
  67. partList: config.map((e) => e.toJson()).toList(),
  68. );
  69. // String filePath = cc["data"]["file_path"];
  70. "[分片上传] cc $cc".w();
  71. return cc;
  72. }

文件上传组件代码

  1. import 'dart:io';
  2. import 'package:LS/common/index.dart';
  3. import 'package:LS/gen/assets.gen.dart';
  4. import 'package:cached_network_image/cached_network_image.dart';
  5. import 'package:file_picker/file_picker.dart';
  6. import 'package:flutter/foundation.dart';
  7. import 'package:flutter/material.dart';
  8. import 'package:flutter_screenutil/flutter_screenutil.dart';
  9. import 'package:get/get.dart';
  10. import 'package:image_picker/image_picker.dart';
  11. enum UploadType {
  12. image,
  13. file,
  14. }
  15. class UploadWidget extends StatefulWidget {
  16. final UploadType type;
  17. final Function(String, int)? onSuccess;
  18. final Function(int, List, UploadType)? onDelete;
  19. final Function()? onPickAssets;
  20. final List<String>? allowedExtensions;
  21. final int? limit;
  22. const UploadWidget({
  23. super.key,
  24. this.type = UploadType.image,
  25. this.onSuccess,
  26. this.onDelete,
  27. this.limit,
  28. this.onPickAssets,
  29. this.allowedExtensions,
  30. });
  31. @override
  32. State<UploadWidget> createState() => _UploadWidgetState();
  33. }
  34. class _UploadWidgetState extends State<UploadWidget> {
  35. // 这两个是上传图片的时候存的
  36. List<Uint8List> webImageList = [];
  37. List<File> appImageList = [];
  38. // 这两个是上传文件的时候存的 文件上传只有 接口上传的时候 有不同所有只要一个
  39. List<FilePickerResult> filesList = [];
  40. FilePickerResult? files;
  41. Widget get curContain {
  42. switch (widget.type) {
  43. case UploadType.image:
  44. return uploadImage();
  45. case UploadType.file:
  46. return uploadFile();
  47. }
  48. }
  49. onPreview(String url) {
  50. if (url.isNotEmpty) {
  51. Get.to(
  52. () => ImagePreviewPage(
  53. imageUrl: url,
  54. ),
  55. );
  56. }
  57. }
  58. // 选择图片
  59. pickImages() async {
  60. Uint8List? webImage;
  61. File? appImage;
  62. XFile? image = await AppToast.getLostData();
  63. if (image != null) {
  64. if (kIsWeb) {
  65. webImage = await image.readAsBytes();
  66. } else {
  67. appImage = File(image.path);
  68. }
  69. }
  70. if (webImage != null) {
  71. webImageList.add(webImage);
  72. }
  73. if (appImage != null) {
  74. appImageList.add(appImage);
  75. }
  76. widget.onPickAssets?.call();
  77. setState(() {});
  78. }
  79. bool isValidExtension(FilePickerResult files) {
  80. return files.files.every((file) {
  81. String extension = (file.extension ?? "").toLowerCase();
  82. return (widget.allowedExtensions ??
  83. [
  84. 'jpg',
  85. 'png',
  86. 'doc',
  87. 'xls',
  88. 'pdf',
  89. 'ppt',
  90. 'docx',
  91. 'xlsx',
  92. 'pptx'
  93. ])
  94. .contains(extension);
  95. });
  96. }
  97. // 选择文件
  98. pickFiles() async {
  99. files = await AppToast.getLostFileData(
  100. allowMultiple: false,
  101. allowedExtensions: (widget.allowedExtensions ??
  102. ['jpg', 'png', 'doc', 'xls', 'pdf', 'ppt', 'docx', 'xlsx', 'pptx']),
  103. );
  104. if (files != null) {
  105. if (!isValidExtension(files as FilePickerResult)) {
  106. AppToast.show("请选择正确的文件格式");
  107. return;
  108. }
  109. filesList.add(files!);
  110. widget.onPickAssets?.call();
  111. setState(() {});
  112. }
  113. }
  114. // 上传图片
  115. Widget uploadImage() {
  116. return SizedBox(
  117. width: double.infinity,
  118. child: GridView.builder(
  119. physics: const NeverScrollableScrollPhysics(),
  120. shrinkWrap: true,
  121. gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  122. crossAxisCount: 4,
  123. crossAxisSpacing: 10,
  124. mainAxisSpacing: 10,
  125. childAspectRatio: 1,
  126. ),
  127. // +1 是为了添加图片按钮
  128. itemCount: widget.limit != null &&
  129. widget.limit! <=
  130. (kIsWeb ? webImageList.length : appImageList.length)
  131. ? (kIsWeb ? webImageList.length : appImageList.length)
  132. : (kIsWeb ? webImageList.length : appImageList.length) + 1,
  133. itemBuilder: (c, i) {
  134. if (kIsWeb) {
  135. if (i >= webImageList.length) {
  136. return addContainer(onTap: pickImages);
  137. }
  138. return UploadingImageWidget(
  139. webImage: webImageList[i],
  140. onDelete: () => onImageDelete(i),
  141. onSuccess: (url) => onSuccess(i, url),
  142. onPreview: onPreview,
  143. );
  144. } else {
  145. if (i >= appImageList.length) {
  146. return addContainer(onTap: pickImages);
  147. }
  148. return UploadingImageWidget(
  149. image: appImageList[i],
  150. onDelete: () => onImageDelete(i),
  151. onSuccess: (url) => onSuccess(i, url),
  152. onPreview: onPreview,
  153. );
  154. }
  155. },
  156. ),
  157. );
  158. }
  159. // 上传文件
  160. Widget uploadFile() {
  161. return SizedBox(
  162. width: double.infinity,
  163. child: GridView.builder(
  164. physics: const NeverScrollableScrollPhysics(),
  165. shrinkWrap: true,
  166. gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  167. crossAxisCount: 4,
  168. crossAxisSpacing: 10,
  169. mainAxisSpacing: 10,
  170. childAspectRatio: 1,
  171. ),
  172. // +1 是为了添加图片按钮
  173. itemCount: widget.limit != null && widget.limit! <= filesList.length
  174. ? filesList.length
  175. : (filesList.length + 1),
  176. itemBuilder: (c, i) {
  177. if (i >= filesList.length) {
  178. return addContainer(onTap: pickFiles);
  179. }
  180. return UploadingFileWidget(
  181. files: filesList[i],
  182. index: i,
  183. onDelete: () => onFileDelete(i),
  184. onSuccess: (url) => onSuccess(i, url),
  185. onPreview: onPreview,
  186. );
  187. },
  188. ),
  189. );
  190. }
  191. onImageDelete(int i) {
  192. if (kIsWeb) {
  193. webImageList.removeAt(i);
  194. widget.onDelete?.call(i, webImageList, UploadType.image);
  195. } else {
  196. appImageList.removeAt(i);
  197. widget.onDelete?.call(i, appImageList, UploadType.image);
  198. }
  199. setState(() {});
  200. }
  201. onFileDelete(int i) {
  202. filesList.removeAt(i);
  203. widget.onDelete?.call(i, filesList, UploadType.file);
  204. setState(() {});
  205. }
  206. onSuccess(int i, String url) {
  207. widget.onSuccess?.call(url, i);
  208. }
  209. // 已上传完成的容器
  210. Widget hasUploadContainer() {
  211. return Container(
  212. width: 75.w,
  213. height: 75.w,
  214. decoration: BoxDecoration(
  215. color: HexColor("#F2F4F7"),
  216. borderRadius: BorderRadius.circular(5.r),
  217. ),
  218. );
  219. }
  220. // 点击添加
  221. Widget addContainer({
  222. Function? onTap,
  223. }) {
  224. return InkWell(
  225. child: Container(
  226. width: 75.w,
  227. height: 75.w,
  228. decoration: BoxDecoration(
  229. color: HexColor("#F2F4F7"),
  230. borderRadius: BorderRadius.circular(5.r),
  231. image: DecorationImage(
  232. image: Assets.images.uploadAdd.provider(),
  233. ),
  234. ),
  235. alignment: Alignment.center,
  236. ),
  237. onTap: () {
  238. onTap?.call();
  239. },
  240. );
  241. }
  242. @override
  243. Widget build(BuildContext context) {
  244. return curContain;
  245. }
  246. }
  247. // 上传图片 上传中的组件
  248. class UploadingImageWidget extends StatefulWidget {
  249. final File? image;
  250. final Uint8List? webImage;
  251. final Function(String)? onSuccess;
  252. final Function()? onFail;
  253. final Function()? onDelete;
  254. final Function(String)? onPreview;
  255. const UploadingImageWidget({
  256. super.key,
  257. this.image,
  258. this.webImage,
  259. this.onSuccess,
  260. this.onFail,
  261. this.onDelete,
  262. this.onPreview,
  263. });
  264. @override
  265. State<UploadingImageWidget> createState() => _UploadingImageWidgetState();
  266. }
  267. class _UploadingImageWidgetState extends State<UploadingImageWidget> {
  268. // 是否上传失败
  269. bool isUploadFail = false;
  270. double cruProgress = 0.0;
  271. String httpPath = "";
  272. // 正在上传中
  273. bool isUploading = false;
  274. @override
  275. void initState() {
  276. super.initState();
  277. initUpload();
  278. }
  279. // 立即进行上传
  280. initUpload() {
  281. try {
  282. kIsWeb ? webUpload() : appUpload();
  283. } catch (e) {
  284. widget.onFail?.call();
  285. setState(() {
  286. isUploadFail = true;
  287. });
  288. }
  289. }
  290. onTapDelete() {
  291. widget.onDelete?.call();
  292. }
  293. webUpload() async {
  294. setState(() {
  295. isUploading = true;
  296. });
  297. final res = await Api.uploadFileListInt(
  298. widget.webImage as Uint8List,
  299. name: "img",
  300. onSendProgress: (count, total) {
  301. setState(() {
  302. cruProgress = count / total;
  303. });
  304. },
  305. );
  306. setState(() {
  307. isUploading = false;
  308. });
  309. httpPath = res["data"] ?? "";
  310. widget.onSuccess?.call(httpPath);
  311. }
  312. appUpload() async {
  313. setState(() {
  314. isUploading = true;
  315. });
  316. final res = await Api.uploadFile(
  317. widget.image!.path,
  318. onSendProgress: (count, total) {
  319. setState(() {
  320. cruProgress = count / total;
  321. });
  322. },
  323. );
  324. setState(() {
  325. isUploading = false;
  326. });
  327. httpPath = res["data"] ?? "";
  328. widget.onSuccess?.call(httpPath);
  329. }
  330. @override
  331. Widget build(BuildContext context) {
  332. return AnimatedContainer(
  333. duration: const Duration(seconds: 1),
  334. width: double.infinity,
  335. height: double.infinity,
  336. decoration: BoxDecoration(
  337. color: HexColor("#F2F4F7"),
  338. borderRadius: BorderRadius.circular(5.r),
  339. ),
  340. child: isUploadFail
  341. ? failUploadContainer()
  342. : (cruProgress == 1.0 && !isUploading
  343. ? finallyUploadContainer()
  344. : beforeUploadContainer()),
  345. );
  346. }
  347. // 上传之前的容器
  348. Stack beforeUploadContainer() {
  349. return Stack(
  350. clipBehavior: Clip.none,
  351. children: [
  352. if (widget.webImage != null)
  353. Container(
  354. width: double.infinity,
  355. height: double.infinity,
  356. clipBehavior: Clip.hardEdge,
  357. decoration: BoxDecoration(
  358. borderRadius: BorderRadius.circular(5.r),
  359. ),
  360. child: Image.memory(
  361. widget.webImage as Uint8List,
  362. width: double.infinity,
  363. height: double.infinity,
  364. ),
  365. ),
  366. if (widget.image != null)
  367. Container(
  368. width: double.infinity,
  369. height: double.infinity,
  370. clipBehavior: Clip.hardEdge,
  371. decoration: BoxDecoration(
  372. borderRadius: BorderRadius.circular(5.r),
  373. ),
  374. child: Image.file(
  375. widget.image as File,
  376. width: double.infinity,
  377. height: double.infinity,
  378. fit: BoxFit.cover,
  379. ),
  380. ),
  381. Positioned.fill(
  382. child: Opacity(
  383. opacity: 0.6,
  384. child: Container(
  385. width: double.infinity,
  386. height: double.infinity,
  387. decoration: BoxDecoration(
  388. color: HexColor("#000000"),
  389. borderRadius: BorderRadius.circular(5.r),
  390. ),
  391. ),
  392. ),
  393. ),
  394. Positioned(
  395. top: -4.w,
  396. right: -4.w,
  397. child: InkWell(
  398. onTap: onTapDelete,
  399. child: Container(
  400. width: 18.w,
  401. height: 18.w,
  402. decoration: const BoxDecoration(
  403. shape: BoxShape.circle,
  404. color: Colors.white,
  405. ),
  406. child: Assets.images.uploadClose.image(width: 18.w),
  407. ),
  408. ),
  409. ),
  410. Positioned.fill(
  411. child: Container(
  412. width: double.infinity,
  413. height: double.infinity,
  414. alignment: Alignment.center,
  415. decoration: BoxDecoration(
  416. borderRadius: BorderRadius.circular(5.r),
  417. ),
  418. child: SizedBox(
  419. width: 40.w,
  420. child: LineProgressWidget(
  421. cruProgress: cruProgress,
  422. minHeight: 5.h,
  423. color: HexColor("#CCCCCC"),
  424. showText: false,
  425. valueColor: AlwaysStoppedAnimation<Color>(HexColor("#F9DE4A")),
  426. ),
  427. ),
  428. ),
  429. ),
  430. ],
  431. );
  432. }
  433. // 完成上传的容器
  434. Stack finallyUploadContainer() {
  435. return Stack(
  436. clipBehavior: Clip.none,
  437. children: [
  438. if (widget.webImage != null)
  439. InkWell(
  440. onTap: () => widget.onPreview?.call(httpPath),
  441. child: Container(
  442. width: double.infinity,
  443. height: double.infinity,
  444. clipBehavior: Clip.hardEdge,
  445. decoration: BoxDecoration(
  446. borderRadius: BorderRadius.circular(5.r),
  447. ),
  448. child: Image.memory(
  449. widget.webImage as Uint8List,
  450. width: double.infinity,
  451. height: double.infinity,
  452. ),
  453. ),
  454. ),
  455. if (widget.image != null)
  456. InkWell(
  457. onTap: () => widget.onPreview?.call(httpPath),
  458. child: Container(
  459. width: double.infinity,
  460. height: double.infinity,
  461. clipBehavior: Clip.hardEdge,
  462. decoration: BoxDecoration(
  463. borderRadius: BorderRadius.circular(5.r),
  464. ),
  465. child: Image.file(
  466. widget.image as File,
  467. width: double.infinity,
  468. height: double.infinity,
  469. fit: BoxFit.cover,
  470. ),
  471. ),
  472. ),
  473. Positioned(
  474. top: -4.w,
  475. right: -4.w,
  476. child: InkWell(
  477. onTap: onTapDelete,
  478. child: Container(
  479. width: 18.w,
  480. height: 18.w,
  481. decoration: const BoxDecoration(
  482. shape: BoxShape.circle,
  483. color: Colors.white,
  484. ),
  485. child: Assets.images.uploadClose.image(width: 18.w),
  486. ),
  487. ),
  488. ),
  489. ],
  490. );
  491. }
  492. // 上传失败重新上传
  493. failReUpload() async {
  494. cruProgress = 0.0;
  495. isUploadFail = false;
  496. setState(() {});
  497. initUpload();
  498. }
  499. // 失败上传的容器
  500. Stack failUploadContainer() {
  501. return Stack(
  502. clipBehavior: Clip.none,
  503. children: [
  504. if (widget.webImage != null)
  505. Container(
  506. width: double.infinity,
  507. height: double.infinity,
  508. clipBehavior: Clip.hardEdge,
  509. decoration: BoxDecoration(
  510. borderRadius: BorderRadius.circular(5.r),
  511. ),
  512. child: Image.memory(
  513. widget.webImage as Uint8List,
  514. width: double.infinity,
  515. height: double.infinity,
  516. ),
  517. ),
  518. if (widget.image != null)
  519. Container(
  520. width: double.infinity,
  521. height: double.infinity,
  522. clipBehavior: Clip.hardEdge,
  523. decoration: BoxDecoration(
  524. borderRadius: BorderRadius.circular(5.r),
  525. ),
  526. child: Image.file(
  527. widget.image as File,
  528. width: double.infinity,
  529. height: double.infinity,
  530. fit: BoxFit.cover,
  531. ),
  532. ),
  533. Positioned.fill(
  534. child: Container(
  535. width: double.infinity,
  536. height: double.infinity,
  537. decoration: BoxDecoration(
  538. borderRadius: BorderRadius.circular(5.r),
  539. color: HexColor("#000000").withOpacity(0.6),
  540. ),
  541. alignment: Alignment.center,
  542. child: InkWell(
  543. onTap: failReUpload,
  544. child: SizedBox(
  545. width: 20.w,
  546. height: 20.w,
  547. child: Assets.images.uploadReload.image(width: 20.w),
  548. ),
  549. ),
  550. ),
  551. ),
  552. Positioned(
  553. top: -4.w,
  554. right: -4.w,
  555. child: InkWell(
  556. onTap: onTapDelete,
  557. child: Container(
  558. width: 18.w,
  559. height: 18.w,
  560. decoration: const BoxDecoration(
  561. shape: BoxShape.circle,
  562. color: Colors.white,
  563. ),
  564. child: Assets.images.uploadClose.image(width: 18.w),
  565. ),
  566. ),
  567. ),
  568. ],
  569. );
  570. }
  571. }
  572. // 上传文件 上传中的组件
  573. class UploadingFileWidget extends StatefulWidget {
  574. final int index;
  575. final FilePickerResult? files;
  576. final Function(String)? onSuccess;
  577. final Function()? onFail;
  578. final Function()? onDelete;
  579. final Function(String)? onPreview;
  580. const UploadingFileWidget({
  581. super.key,
  582. this.files,
  583. required this.index,
  584. this.onSuccess,
  585. this.onFail,
  586. this.onDelete,
  587. this.onPreview,
  588. });
  589. @override
  590. State<UploadingFileWidget> createState() => _UploadingFileWidgetState();
  591. }
  592. class _UploadingFileWidgetState extends State<UploadingFileWidget> {
  593. // 是否上传失败
  594. bool isUploadFail = false;
  595. // 正在上传中
  596. bool isUploading = false;
  597. double cruProgress = 0.0;
  598. String httpPath = "";
  599. Function? cancelSendItems;
  600. @override
  601. void initState() {
  602. super.initState();
  603. initUpload();
  604. }
  605. // 立即进行上传
  606. initUpload() {
  607. try {
  608. kIsWeb ? webUpload() : appUpload();
  609. } catch (e) {
  610. widget.onFail?.call();
  611. setState(() {
  612. isUploadFail = true;
  613. });
  614. }
  615. }
  616. onTapDelete() {
  617. widget.onDelete?.call();
  618. if (cancelSendItems != null) {
  619. cancelSendItems!.call();
  620. }
  621. }
  622. webUpload() async {
  623. PlatformFile curFile = widget.files!.files.first;
  624. setState(() {
  625. isUploading = true;
  626. });
  627. final res = await Api.uploadFilePlatformFile(
  628. curFile,
  629. onSendProgress: (count, total) {
  630. setState(() {
  631. cruProgress = count / total;
  632. });
  633. },
  634. );
  635. httpPath = res["data"] ?? "";
  636. setState(() {
  637. isUploading = false;
  638. });
  639. widget.onSuccess?.call(httpPath);
  640. }
  641. appUpload() async {
  642. var path = widget.files!.paths.first;
  643. int size = widget.files?.files.first.size ?? 0;
  644. if (size > FileUtils.mToSize(20)) {
  645. appSliceUpload();
  646. return;
  647. }
  648. setState(() {
  649. isUploading = true;
  650. });
  651. final res = await Api.uploadFile(
  652. path as String,
  653. onSendProgress: (count, total) async {
  654. // await Future.delayed(const Duration(seconds: 1));
  655. setState(() {
  656. cruProgress = count / total;
  657. });
  658. },
  659. );
  660. setState(() {
  661. isUploading = false;
  662. });
  663. httpPath = res["data"] ?? "";
  664. widget.onSuccess?.call(httpPath);
  665. }
  666. // 大文件切片上传
  667. appSliceUpload() async {
  668. var path = widget.files!.paths.first;
  669. setState(() {
  670. isUploading = true;
  671. });
  672. final res = await Api.uploadSliceFile(
  673. path as String,
  674. onSendProgress: (count, total) async {
  675. // await Future.delayed(const Duration(seconds: 1));
  676. setState(() {
  677. cruProgress = count / total;
  678. });
  679. },
  680. getFileUtils: (utils) {
  681. "[分片上传] 获取 utils $utils".w();
  682. cancelSendItems = () => utils.cancelSendItems();
  683. },
  684. );
  685. setState(() {
  686. isUploading = false;
  687. });
  688. httpPath = res["data"] ?? "";
  689. widget.onSuccess?.call(httpPath);
  690. }
  691. @override
  692. Widget build(BuildContext context) {
  693. return AnimatedContainer(
  694. duration: const Duration(seconds: 1),
  695. width: double.infinity,
  696. height: double.infinity,
  697. decoration: BoxDecoration(
  698. color: HexColor("#F2F4F7"),
  699. borderRadius: BorderRadius.circular(5.r),
  700. ),
  701. child: isUploadFail
  702. ? failUploadContainer()
  703. : (cruProgress == 1.0 && !isUploading
  704. ? finallyUploadContainer()
  705. : beforeUploadContainer()),
  706. );
  707. }
  708. // 上传之前的容器
  709. Stack beforeUploadContainer() {
  710. return Stack(
  711. clipBehavior: Clip.none,
  712. children: [
  713. if (widget.files?.files.first != null)
  714. fileInfoContainer(widget.files?.files.first),
  715. Positioned.fill(
  716. child: Opacity(
  717. opacity: 0.6,
  718. child: Container(
  719. width: double.infinity,
  720. height: double.infinity,
  721. decoration: BoxDecoration(
  722. color: HexColor("#000000"),
  723. borderRadius: BorderRadius.circular(5.r),
  724. ),
  725. ),
  726. ),
  727. ),
  728. Positioned.fill(
  729. child: Container(
  730. width: double.infinity,
  731. height: double.infinity,
  732. alignment: Alignment.center,
  733. decoration: BoxDecoration(
  734. borderRadius: BorderRadius.circular(5.r),
  735. ),
  736. child: SizedBox(
  737. width: 40.w,
  738. child: LineProgressWidget(
  739. cruProgress: cruProgress,
  740. minHeight: 5.h,
  741. color: HexColor("#CCCCCC"),
  742. showText: false,
  743. valueColor: AlwaysStoppedAnimation<Color>(HexColor("#F9DE4A")),
  744. ),
  745. ),
  746. ),
  747. ),
  748. Positioned(
  749. top: -4.w,
  750. right: -4.w,
  751. child: InkWell(
  752. onTap: onTapDelete,
  753. child: Container(
  754. width: 18.w,
  755. height: 18.w,
  756. decoration: const BoxDecoration(
  757. shape: BoxShape.circle,
  758. color: Colors.white,
  759. ),
  760. child: Assets.images.uploadClose.image(width: 18.w),
  761. ),
  762. ),
  763. ),
  764. ],
  765. );
  766. }
  767. // 文件信息展示容器
  768. Widget fileInfoContainer(PlatformFile? file) {
  769. String fileName = file?.name ?? "";
  770. if (Utils.isImageFile(fileName)) {
  771. if (kIsWeb) {
  772. Uint8List webImageFile = file?.bytes as Uint8List;
  773. return InkWell(
  774. onTap: () => widget.onPreview?.call(httpPath),
  775. child: Container(
  776. width: double.infinity,
  777. height: double.infinity,
  778. clipBehavior: Clip.hardEdge,
  779. decoration: BoxDecoration(
  780. borderRadius: BorderRadius.circular(5.r),
  781. ),
  782. child: Image.memory(
  783. webImageFile,
  784. width: double.infinity,
  785. height: double.infinity,
  786. ),
  787. ),
  788. );
  789. } else {
  790. File imageFile = File(file?.path ?? "");
  791. return InkWell(
  792. onTap: () => widget.onPreview?.call(httpPath),
  793. child: Container(
  794. width: double.infinity,
  795. height: double.infinity,
  796. clipBehavior: Clip.hardEdge,
  797. decoration: BoxDecoration(
  798. borderRadius: BorderRadius.circular(5.r),
  799. ),
  800. child: Image.file(
  801. imageFile,
  802. width: double.infinity,
  803. height: double.infinity,
  804. fit: BoxFit.cover,
  805. ),
  806. ),
  807. );
  808. }
  809. }
  810. return Container(
  811. width: double.infinity,
  812. height: double.infinity,
  813. clipBehavior: Clip.hardEdge,
  814. decoration: BoxDecoration(
  815. borderRadius: BorderRadius.circular(5.r),
  816. ),
  817. alignment: Alignment.center,
  818. child: Column(
  819. mainAxisSize: MainAxisSize.min,
  820. crossAxisAlignment: CrossAxisAlignment.center,
  821. mainAxisAlignment: MainAxisAlignment.center,
  822. children: [
  823. Assets.images.uploadFileIcon.image(width: 20.w),
  824. SizedBox(height: 5.h),
  825. Text(
  826. fileName,
  827. style: TextStyle(
  828. fontFamily: Font.pingFang,
  829. fontWeight: FontWeight.w500,
  830. fontSize: 12.sp,
  831. color: HexColor("#1A1A1A"),
  832. height: 1.1,
  833. ),
  834. textAlign: TextAlign.center,
  835. overflow: TextOverflow.ellipsis,
  836. maxLines: 3,
  837. ),
  838. ],
  839. ),
  840. );
  841. }
  842. // 完成上传的容器
  843. Stack finallyUploadContainer() {
  844. return Stack(
  845. clipBehavior: Clip.none,
  846. children: [
  847. if (widget.files?.files.first != null)
  848. fileInfoContainer(widget.files?.files.first),
  849. Positioned(
  850. top: -4.w,
  851. right: -4.w,
  852. child: InkWell(
  853. onTap: onTapDelete,
  854. child: Container(
  855. width: 18.w,
  856. height: 18.w,
  857. decoration: const BoxDecoration(
  858. shape: BoxShape.circle,
  859. color: Colors.white,
  860. ),
  861. child: Assets.images.uploadClose.image(width: 18.w),
  862. ),
  863. ),
  864. ),
  865. ],
  866. );
  867. }
  868. // 上传失败重新上传
  869. failReUpload() async {
  870. cruProgress = 0.0;
  871. isUploadFail = false;
  872. setState(() {});
  873. initUpload();
  874. }
  875. // 失败上传的容器
  876. Stack failUploadContainer() {
  877. return Stack(
  878. clipBehavior: Clip.none,
  879. children: [
  880. if (widget.files?.files.first != null)
  881. fileInfoContainer(widget.files?.files.first),
  882. Positioned.fill(
  883. child: Container(
  884. width: double.infinity,
  885. height: double.infinity,
  886. decoration: BoxDecoration(
  887. borderRadius: BorderRadius.circular(5.r),
  888. color: HexColor("#000000").withOpacity(0.6),
  889. ),
  890. alignment: Alignment.center,
  891. child: InkWell(
  892. onTap: failReUpload,
  893. child: SizedBox(
  894. width: 20.w,
  895. height: 20.w,
  896. child: Assets.images.uploadReload.image(width: 20.w),
  897. ),
  898. ),
  899. ),
  900. ),
  901. Positioned(
  902. top: -4.w,
  903. right: -4.w,
  904. child: InkWell(
  905. onTap: onTapDelete,
  906. child: Container(
  907. width: 18.w,
  908. height: 18.w,
  909. decoration: const BoxDecoration(
  910. shape: BoxShape.circle,
  911. color: Colors.white,
  912. ),
  913. child: Assets.images.uploadClose.image(width: 18.w),
  914. ),
  915. ),
  916. ),
  917. ],
  918. );
  919. }
  920. }
  921. // 已上传图片或文件展示
  922. class HasUploadShowWidget extends StatelessWidget {
  923. final List<String?> urls;
  924. final Function(int)? onDelete;
  925. final bool showDelete;
  926. final Function(String)? onFileTap;
  927. final TextDirection textDirection;
  928. const HasUploadShowWidget({
  929. super.key,
  930. required this.urls,
  931. this.onDelete,
  932. this.showDelete = true,
  933. this.onFileTap,
  934. this.textDirection = TextDirection.ltr,
  935. });
  936. onTapDelete(int idx) {
  937. onDelete?.call(idx);
  938. }
  939. onPreview(String url) {
  940. if (url.isNotEmpty) {
  941. Get.to(
  942. () => ImagePreviewPage(
  943. imageUrl: url,
  944. ),
  945. );
  946. }
  947. }
  948. @override
  949. Widget build(BuildContext context) {
  950. return SizedBox(
  951. width: double.infinity,
  952. child: Directionality(
  953. textDirection: textDirection,
  954. child: GridView.builder(
  955. shrinkWrap: true,
  956. itemCount: urls.length,
  957. physics: const NeverScrollableScrollPhysics(),
  958. gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  959. crossAxisCount: 4,
  960. crossAxisSpacing: 10,
  961. mainAxisSpacing: 10,
  962. childAspectRatio: 1,
  963. ),
  964. itemBuilder: (c, i) {
  965. if (Utils.isImageFile(urls[i] ?? "")) {
  966. return Stack(
  967. clipBehavior: Clip.none,
  968. children: [
  969. InkWell(
  970. onTap: () => onPreview(urls[i] ?? ""),
  971. child: Container(
  972. width: 75.w,
  973. height: 75.w,
  974. clipBehavior: Clip.hardEdge,
  975. decoration: BoxDecoration(
  976. borderRadius: BorderRadius.circular(5.r),
  977. ),
  978. child: urls[i] != null
  979. ? CachedNetworkImage(
  980. width: 75.w,
  981. height: 75.w,
  982. imageUrl: urls[i] ?? "",
  983. fit: BoxFit.cover,
  984. )
  985. : null,
  986. ),
  987. ),
  988. if (showDelete)
  989. Positioned(
  990. top: -4.w,
  991. right: -4.w,
  992. child: InkWell(
  993. onTap: () => onTapDelete(i),
  994. child: Container(
  995. width: 18.w,
  996. height: 18.w,
  997. decoration: const BoxDecoration(
  998. shape: BoxShape.circle,
  999. color: Colors.white,
  1000. ),
  1001. child: Assets.images.uploadClose.image(width: 18.w),
  1002. ),
  1003. ),
  1004. ),
  1005. ],
  1006. );
  1007. }
  1008. return Stack(
  1009. clipBehavior: Clip.none,
  1010. children: [
  1011. InkWell(
  1012. onTap: () => onFileTap?.call(urls[i] ?? ""),
  1013. child: Container(
  1014. width: 75.w,
  1015. height: 75.w,
  1016. clipBehavior: Clip.none,
  1017. decoration: BoxDecoration(
  1018. borderRadius: BorderRadius.circular(5.r),
  1019. color: HexColor("#F2F4F7"),
  1020. ),
  1021. alignment: Alignment.center,
  1022. child: Column(
  1023. crossAxisAlignment: CrossAxisAlignment.center,
  1024. mainAxisAlignment: MainAxisAlignment.center,
  1025. children: [
  1026. Assets.images.uploadFileIcon.image(width: 20.w),
  1027. SizedBox(height: 5.h),
  1028. Container(
  1029. constraints: BoxConstraints(maxWidth: 75.w),
  1030. child: Text(
  1031. Utils.getFileNameFromUrl((urls[i] ?? "")),
  1032. style: TextStyle(
  1033. fontFamily: Font.pingFang,
  1034. fontWeight: FontWeight.w500,
  1035. fontSize: 12.sp,
  1036. color: HexColor("#1A1A1A"),
  1037. height: 1.1,
  1038. ),
  1039. textAlign: TextAlign.center,
  1040. overflow: TextOverflow.ellipsis,
  1041. maxLines: 2,
  1042. ),
  1043. ),
  1044. ],
  1045. ),
  1046. ),
  1047. ),
  1048. if (showDelete)
  1049. Positioned(
  1050. top: -4.w,
  1051. right: -4.w,
  1052. child: InkWell(
  1053. onTap: () => onTapDelete(i),
  1054. child: Container(
  1055. width: 18.w,
  1056. height: 18.w,
  1057. decoration: const BoxDecoration(
  1058. shape: BoxShape.circle,
  1059. color: Colors.white,
  1060. ),
  1061. child: Assets.images.uploadClose.image(width: 18.w),
  1062. ),
  1063. ),
  1064. ),
  1065. ],
  1066. );
  1067. }),
  1068. ),
  1069. );
  1070. }
  1071. }

使用 文件上传 (如果上传的是图片 显示的也是图片样式)

  1. UploadWidget(
  2. type: UploadType.file,
  3. limit: 5 - controller.lastFiles.length,
  4. onPickAssets: () {
  5. controller.curUploadCount++;
  6. },
  7. onDelete: (i, list, t) {
  8. controller.curUploadCount--;
  9. controller.state.files.removeAt(i);
  10. controller.update();
  11. },
  12. onSuccess: (url, i) {
  13. controller.curUploadCount--;
  14. controller.state.files.add(url);
  15. controller.update();
  16. },
  17. )

图片上传

  1. UploadWidget(
  2. type: UploadType.image,
  3. limit: 9,
  4. onPickAssets: () {
  5. curUploadCount++;
  6. setState(() {});
  7. },
  8. onDelete: (i, list, t) {
  9. curUploadCount--;
  10. print("文件 -- $curUploadCount");
  11. imagesFiles.removeAt(i);
  12. setState(() {});
  13. },
  14. onSuccess: (url, i) {
  15. curUploadCount--;
  16. // controller.state.files.add(url);
  17. imagesFiles.add(url);
  18. setState(() {});
  19. },
  20. ),

支持撤销文件上传

断点续传功能和秒传

在原有的基础上改动如下

所有上传接口都加上文件的MD5 值,分片的几个接口将uploadId改为整个文件的MD5

新增MD5的方法 依旧使用crypto 库

crypto | Dart PackageImplementations of SHA, MD5, and HMAC cryptographic functions.icon-default.png?t=N7T8https://pub-web.flutter-io.cn/packages/crypto

  1. static staticCalculateMD5(File file) async {
  2. if (!file.existsSync()) {
  3. print('File "$file" does not exist.');
  4. return;
  5. }
  6. Digest digest = await md5.bind(file.openRead()).first;
  7. return digest.toString();
  8. }

 app 使用

  1. FormData formData = FormData.fromMap({
  2. 'file': await MultipartFile.fromFile(path),
  3. 'md5': await FileUtils.staticCalculateMD5(File(path)),
  4. });

web端使用

  1. static staticCalculateMD5Stream(List<int> input) async {
  2. Digest digest = md5.convert(input);
  3. return digest.toString();
  4. }
  1. FormData formData = FormData.fromMap({
  2. 'file': multipartFile,
  3. 'md5': await FileUtils.staticCalculateMD5Stream(fileBytes),
  4. });

分片接口改动如下

1、初始化分片接口

新增参数 md5 文件的MD5  这样就可以验证文件是否上传过,如果上传直接返回文件地址

未上传完 会返回已上传的分片 然后对求出未上传的分片进行继续上传 

逻辑修改如下

  1. String filePath = aa['data']['filePath'] ?? "";
  2. List<SliceChunkItem> sendSliceConfig = config;
  3. int finalUploadSliceCount = 0;
  4. // 说明是上传过的文件 直接秒传
  5. if (filePath.isNotEmpty) {
  6. onSendProgress?.call(1, 1);
  7. return aa;
  8. } else {
  9. List partList = (aa['data']['partList'] ?? []);
  10. List<SliceChunkItem> filterPartList = partList
  11. .map<SliceChunkItem>((e) => SliceChunkItem.fromJson(e))
  12. .toList();
  13. for (var it in filterPartList) {
  14. int idx = config.indexWhere((e) => e.partNumber == it.partNumber);
  15. if (idx != -1) {
  16. config[idx] = it;
  17. }
  18. }
  19. sendSliceConfig =
  20. config.where((e) => !(e.end == 0 && e.start == 0)).toList();
  21. if (sendSliceConfig.isNotEmpty) {
  22. finalUploadSliceCount = filterPartList.length;
  23. onSendProgress?.call(finalUploadSliceCount, config.length);
  24. }
  25. }

2、分片的接口 新增了文件的MD5

 完成接口一样的新增md5

最后最新的分片上传接口逻辑如下

 

  1. // 文件分片上传
  2. static uploadSliceFile(
  3. String path, {
  4. ProgressCallback? onSendProgress,
  5. required Function(FileUtils) getFileUtils,
  6. }) async {
  7. File file = File(path);
  8. String fileName = file.path.split('/').last;
  9. final utils = FileUtils(file);
  10. getFileUtils.call(utils);
  11. List<SliceChunkItem> config = await utils.getJsonFromSplitFileIntoChunks();
  12. String curMd5Code = utils.hash;
  13. if (curMd5Code.isEmpty) {
  14. curMd5Code = await FileUtils.staticCalculateMD5(file);
  15. }
  16. final aa = await multipartUploadInit(
  17. fileName: fileName,
  18. checksumType: FileUtils.hashMethod,
  19. md5: curMd5Code,
  20. );
  21. String filePath = aa['data']['filePath'] ?? "";
  22. List<SliceChunkItem> sendSliceConfig = config;
  23. int finalUploadSliceCount = 0;
  24. // 说明是上传过的文件 直接秒传
  25. if (filePath.isNotEmpty) {
  26. onSendProgress?.call(1, 1);
  27. return aa;
  28. } else {
  29. List partList = (aa['data']['partList'] ?? []);
  30. List<SliceChunkItem> filterPartList = partList
  31. .map<SliceChunkItem>((e) => SliceChunkItem.fromJson(e))
  32. .toList();
  33. for (var it in filterPartList) {
  34. int idx = config.indexWhere((e) => e.partNumber == it.partNumber);
  35. if (idx != -1) {
  36. config[idx] = it;
  37. }
  38. }
  39. sendSliceConfig =
  40. config.where((e) => !(e.end == 0 && e.start == 0)).toList();
  41. if (sendSliceConfig.isNotEmpty) {
  42. finalUploadSliceCount = filterPartList.length;
  43. onSendProgress?.call(finalUploadSliceCount, config.length);
  44. }
  45. }
  46. // String uploadId = aa['data']['uploadId'];
  47. "[分片上传] aa $aa".w();
  48. FormData formData;
  49. await utils.sendItems(
  50. config: sendSliceConfig,
  51. concurrentLimit: 4,
  52. callback: (item) async {
  53. // item.setUploadId(uploadId);
  54. "[分片上传] bb 开始上传 partNumber ${item.partNumber} ".w();
  55. var fileBytes = await utils.getRange(item.start ?? 0, item.end ?? 0);
  56. item.checksum = utils.calculateSHA1FormList(fileBytes);
  57. // 直接传递数组fileBytes 给dio 会导致内存崩溃
  58. formData = FormData.fromMap({
  59. 'file': MultipartFile.fromBytes(fileBytes, filename: "11"),
  60. 'partNumber': item.partNumber,
  61. 'checksum': item.checksum,
  62. 'md5': curMd5Code,
  63. });
  64. final b = await multipartUpload(formData: formData);
  65. finalUploadSliceCount++;
  66. onSendProgress?.call(finalUploadSliceCount, config.length);
  67. "[分片上传] bb 结束上传 partNumber ${item.partNumber} $b".w();
  68. String tag = b["data"]["tag"];
  69. item.setTag(tag);
  70. });
  71. final cc = await multipartUploadComplete(
  72. // checksum: checksum,
  73. // uploadId: uploadId,
  74. md5: curMd5Code,
  75. partList: config.map((e) => e.toJson()).toList(),
  76. );
  77. // String filePath = cc["data"]["file_path"];
  78. "[分片上传] cc $cc".w();
  79. return cc;
  80. }

上传组件发现删除存在bug 修复如下

UploadingFileWidget 组件使用key: ValueKey('image_$i'),进行标识

  1. GridView.builder(
  2. physics: const NeverScrollableScrollPhysics(),
  3. shrinkWrap: true,
  4. gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  5. crossAxisCount: 4,
  6. crossAxisSpacing: 10,
  7. mainAxisSpacing: 10,
  8. childAspectRatio: 1,
  9. ),
  10. // +1 是为了添加图片按钮
  11. itemCount: widget.limit != null && widget.limit! <= filesList.length
  12. ? filesList.length
  13. : (filesList.length + 1),
  14. itemBuilder: (c, i) {
  15. if (i >= filesList.length) {
  16. return addContainer(onTap: pickFiles);
  17. }
  18. return UploadingFileWidget(
  19. files: filesList[i],
  20. index: i,
  21. onDelete: () => onFileDelete(i),
  22. onSuccess: (url) => onSuccess(i, url),
  23. onPreview: onPreview,
  24. key: ValueKey('image_$i'),
  25. );
  26. },
  27. ),

在Flutter中,Key可以是任何类型的对象,但最常用的是 GlobalKey、ValueKey 和 ObjectKey。

  1. GlobalKey: 用于在整个应用程序中唯一标识一个Widget。当你需要在程序的不同部分引用同一个组件时,可以使用GlobalKey。比如,如果你需要通过GlobalKey在一个页面中的某个组件,可以使用GlobalKey。

  2. ValueKey: 用于基于值的比较,可以根据给定的值来标识Widget,在列表、集合或父子关系中非常有用。比如,如果你有一个具有一组项目的列表,并且需要标识这些项目,可以使用ValueKey,并以项目的唯一标识符作为值。

  3. ObjectKey: 与ValueKey类似,可以根据对象的身份来标识Widget。如果你需要根据对象的身份来标识Widget,而不是基于对象的值,可以使用ObjectKey。

除了这些内置的Key类型,你也可以创建自定义的Key类,只要它们遵循Key的方法和属性即可。

在你的情况下,你可以使用GlobalKey来保证每个UploadingImageWidget都有唯一的标识,这样就可以避免状态混淆的问题。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/124405
推荐阅读
相关标签
  

闽ICP备14008679号