storage.dart 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:typed_data';
  5. import 'package:fis_common/logger/logger.dart';
  6. import 'package:fis_jsonrpc/rpc.dart';
  7. import 'package:http/http.dart' as http;
  8. import 'package:image_picker/image_picker.dart';
  9. import 'package:path_provider/path_provider.dart';
  10. import 'package:vitalapp/architecture/utils/prompt_box.dart';
  11. import 'package:vitalapp/rpc.dart';
  12. import 'package:vitalapp/store/store.dart';
  13. /// 部分分段返回的结果
  14. class PartFileResultInfo {
  15. /// 分片上传的文件地址
  16. String fileUrl;
  17. /// 分片上传的eTag
  18. String eTag;
  19. /// 分块的uploadId
  20. String uploadId;
  21. /// 分块的下标
  22. int partNumber;
  23. PartFileResultInfo({
  24. required this.fileUrl,
  25. required this.eTag,
  26. required this.uploadId,
  27. required this.partNumber,
  28. });
  29. }
  30. /// 分段上传文件
  31. class PartUploadFileInfo {
  32. /// 分片的下标
  33. int partNumber;
  34. /// 初始化生成的uploadId
  35. String uploadId;
  36. /// 分片文件的二进制数据
  37. Uint8List fileBytes;
  38. PartUploadFileInfo({
  39. required this.partNumber,
  40. required this.uploadId,
  41. required this.fileBytes,
  42. });
  43. }
  44. ///存储上传文件基本信息
  45. class StorageUploadFileInfo {
  46. ///文件token
  47. String fileToken;
  48. ///文件的二进制数据
  49. Uint8List fileBytes;
  50. ///文件名
  51. String fileName;
  52. ///文件模拟类型
  53. String? mimeType;
  54. /// 文件大小
  55. int? fileSize;
  56. StorageUploadFileInfo({
  57. required this.fileToken,
  58. required this.fileBytes,
  59. required this.fileName,
  60. this.mimeType,
  61. this.fileSize,
  62. });
  63. }
  64. ///存储上传请求
  65. class StorageUploadRequest {
  66. StorageUploadFileInfo fileInfo;
  67. StorageUploadRequest({
  68. required this.fileInfo,
  69. });
  70. }
  71. ///web的存储API
  72. class StorageWebApi {
  73. Future<bool> testApi() async => false;
  74. }
  75. ///存储服务扩展类
  76. extension StorageServiceExt on StorageService {
  77. ///鉴权 TODO: fileName 为空则接口报错,所以此处设置一个默认值
  78. Future<StorageServiceSettingDTO> getAuth({
  79. String? fileName,
  80. bool? isRechristen,
  81. List<DataItemDTO>? urlParams,
  82. List<DataItemDTO>? headerParams,
  83. String? requestMethod,
  84. }) async {
  85. try {
  86. final result = await rpc.storage.getAuthorizationAsync(FileServiceRequest(
  87. token: Store.user.token,
  88. fileName: fileName ?? "dat",
  89. isRechristen: isRechristen ?? true,
  90. urlParams: urlParams,
  91. headerParams: headerParams,
  92. requestMethod: requestMethod,
  93. ));
  94. return result;
  95. } catch (e) {
  96. return StorageServiceSettingDTO();
  97. }
  98. }
  99. /// 图片上传
  100. Future<String?> upload(XFile xfile, {String? fileType}) async {
  101. try {
  102. final auth = await getAuth(fileName: fileType);
  103. final bytes = await xfile.readAsBytes();
  104. Map<String, String> params = {};
  105. params['Authorization'] = auth.authorization!;
  106. params['ContentType'] = auth.contentType!;
  107. final response = await http
  108. .put(
  109. Uri.parse(auth.storageUrl!),
  110. body: bytes,
  111. headers: params,
  112. )
  113. .timeout(
  114. const Duration(seconds: 30),
  115. );
  116. if (response.statusCode == 200) {
  117. return auth.storageUrl!;
  118. }
  119. } catch (e) {
  120. PromptBox.toast('上传失败');
  121. logger.e("file upload error", e);
  122. return null;
  123. }
  124. return null;
  125. }
  126. // 将字符串写入文件
  127. Future<File> writeStringToFile(String content) async {
  128. final tempDir = await getTemporaryDirectory();
  129. final tempFile = File('${tempDir.path}/temp.txt');
  130. await tempFile.writeAsString(content);
  131. return tempFile;
  132. }
  133. // 文件上传
  134. Future<String?> uploadFile(File file) async {
  135. try {
  136. final auth = await getAuth();
  137. final bytes = await file.readAsBytes();
  138. Map<String, String> params = {};
  139. params['Authorization'] = auth.authorization!;
  140. params['ContentType'] = auth.contentType!;
  141. final response = await http
  142. .put(
  143. Uri.parse(auth.storageUrl!),
  144. body: bytes,
  145. headers: params,
  146. )
  147. .timeout(
  148. const Duration(seconds: 30),
  149. );
  150. if (response.statusCode == 200) {
  151. return auth.storageUrl!;
  152. }
  153. } catch (e) {
  154. PromptBox.toast('上传失败');
  155. logger.e("file upload error", e);
  156. return null;
  157. }
  158. return null;
  159. }
  160. ///文件上传(base64)
  161. Future<String?> uploadBase64File(String base64Str, String name) async {
  162. try {
  163. var buffer = base64.decode(base64Str);
  164. return uploadUint8List(buffer, name);
  165. } catch (e) {
  166. logger.e("file upload error", e);
  167. }
  168. return null;
  169. }
  170. ///文件上传(UInt8List)
  171. Future<String?> uploadUint8List(Uint8List buffer, String name,
  172. [bool? isRechristen]) async {
  173. try {
  174. var nameInfos = name.split('.');
  175. final auth = await getAuth(
  176. fileName: nameInfos.last,
  177. isRechristen: isRechristen,
  178. );
  179. Map<String, String> params = {};
  180. params['Authorization'] = auth.authorization!;
  181. params['ContentType'] = auth.contentType!;
  182. final response = await http
  183. .put(
  184. Uri.parse(auth.storageUrl!),
  185. body: buffer,
  186. headers: params,
  187. )
  188. .timeout(
  189. const Duration(seconds: 30),
  190. );
  191. if (response.statusCode == 200) {
  192. return auth.storageUrl;
  193. }
  194. } catch (e) {
  195. logger.e('StorageServiceExt uploadUint8List ex:$e');
  196. }
  197. return null;
  198. }
  199. }