storage.dart 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. import 'package:universal_html/html.dart' as html;
  14. /// 部分分段返回的结果
  15. class PartFileResultInfo {
  16. /// 分片上传的文件地址
  17. String fileUrl;
  18. /// 分片上传的eTag
  19. String eTag;
  20. /// 分块的uploadId
  21. String uploadId;
  22. /// 分块的下标
  23. int partNumber;
  24. PartFileResultInfo({
  25. required this.fileUrl,
  26. required this.eTag,
  27. required this.uploadId,
  28. required this.partNumber,
  29. });
  30. }
  31. /// 分段上传文件
  32. class PartUploadFileInfo {
  33. /// 分片的下标
  34. int partNumber;
  35. /// 初始化生成的uploadId
  36. String uploadId;
  37. /// 分片文件的二进制数据
  38. Uint8List fileBytes;
  39. PartUploadFileInfo({
  40. required this.partNumber,
  41. required this.uploadId,
  42. required this.fileBytes,
  43. });
  44. }
  45. ///存储上传文件基本信息
  46. class StorageUploadFileInfo {
  47. ///文件token
  48. String fileToken;
  49. ///文件的二进制数据
  50. Uint8List fileBytes;
  51. ///文件名
  52. String fileName;
  53. ///文件模拟类型
  54. String? mimeType;
  55. /// 文件大小
  56. int? fileSize;
  57. StorageUploadFileInfo({
  58. required this.fileToken,
  59. required this.fileBytes,
  60. required this.fileName,
  61. this.mimeType,
  62. this.fileSize,
  63. });
  64. }
  65. ///存储上传请求
  66. class StorageUploadRequest {
  67. StorageUploadFileInfo fileInfo;
  68. StorageUploadRequest({
  69. required this.fileInfo,
  70. });
  71. }
  72. ///web的存储API
  73. class StorageWebApi {
  74. Future<bool> testApi() async => false;
  75. }
  76. ///存储服务扩展类
  77. extension StorageServiceExt on StorageService {
  78. ///鉴权 TODO: fileName 为空则接口报错,所以此处设置一个默认值
  79. Future<StorageServiceSettingDTO> getAuth({
  80. String? fileName,
  81. bool? isRechristen,
  82. List<DataItemDTO>? urlParams,
  83. List<DataItemDTO>? headerParams,
  84. String? requestMethod,
  85. }) async {
  86. try {
  87. final result = await rpc.storage.getAuthorizationAsync(FileServiceRequest(
  88. token: Store.user.token,
  89. fileName: fileName ?? "dat",
  90. isRechristen: isRechristen ?? true,
  91. urlParams: urlParams,
  92. headerParams: headerParams,
  93. requestMethod: requestMethod,
  94. ));
  95. return result;
  96. } catch (e) {
  97. return StorageServiceSettingDTO();
  98. }
  99. }
  100. /// 图片上传
  101. Future<String?> upload(XFile xfile, {String? fileType}) async {
  102. try {
  103. final auth = await getAuth(fileName: fileType);
  104. final bytes = await xfile.readAsBytes();
  105. Map<String, String> params = {};
  106. params['Authorization'] = auth.authorization!;
  107. params['ContentType'] = auth.contentType!;
  108. final response = await http
  109. .put(
  110. Uri.parse(auth.storageUrl!),
  111. body: bytes,
  112. headers: params,
  113. )
  114. .timeout(
  115. const Duration(seconds: 30),
  116. );
  117. if (response.statusCode == 200) {
  118. return auth.storageUrl!;
  119. }
  120. } catch (e) {
  121. PromptBox.toast('上传失败');
  122. logger.e("file upload error", e);
  123. return null;
  124. }
  125. return null;
  126. }
  127. /// web 端图片上传
  128. Future<String?> webUpload(html.File file, {String? fileType}) async {
  129. try {
  130. final auth = await getAuth(fileName: fileType);
  131. final bytes = await readBytesFromHtmlFile(file);
  132. Map<String, String> params = {};
  133. params['Authorization'] = auth.authorization!;
  134. params['ContentType'] = auth.contentType!;
  135. final response = await http
  136. .put(
  137. Uri.parse(auth.storageUrl!),
  138. body: bytes,
  139. headers: params,
  140. )
  141. .timeout(
  142. const Duration(seconds: 30),
  143. );
  144. if (response.statusCode == 200) {
  145. return auth.storageUrl!;
  146. }
  147. } catch (e) {
  148. PromptBox.toast('上传失败');
  149. logger.e("file upload error", e);
  150. return null;
  151. }
  152. return null;
  153. }
  154. Future<List<int>> readBytesFromHtmlFile(html.File file) async {
  155. final completer = Completer<List<int>>();
  156. final reader = html.FileReader();
  157. reader.onLoadEnd.listen((html.ProgressEvent event) {
  158. final result = reader.result;
  159. completer.complete(result as FutureOr<List<int>>?);
  160. });
  161. reader.onError.listen((html.ProgressEvent event) {
  162. completer.completeError('Error reading file');
  163. });
  164. reader.readAsArrayBuffer(file);
  165. return completer.future;
  166. }
  167. // 将字符串写入文件
  168. Future<File> writeStringToFile(String content) async {
  169. final tempDir = await getTemporaryDirectory();
  170. final tempFile = File('${tempDir.path}/temp.txt');
  171. await tempFile.writeAsString(content);
  172. return tempFile;
  173. }
  174. // 文件上传
  175. Future<String?> uploadFile(File file) async {
  176. try {
  177. final auth = await getAuth();
  178. final bytes = await file.readAsBytes();
  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: bytes,
  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. PromptBox.toast('上传失败');
  196. logger.e("file upload error", e);
  197. return null;
  198. }
  199. return null;
  200. }
  201. // 将字符串转换成UintList
  202. Future<Uint8List> writeStringToByte(String content) async {
  203. List<int> bytes = utf8.encode(content);
  204. Uint8List uint8List = Uint8List.fromList(bytes);
  205. return uint8List;
  206. }
  207. // UintList上传
  208. Future<String?> uploadByte(Uint8List uint8List) async {
  209. try {
  210. final auth = await getAuth();
  211. Map<String, String> params = {};
  212. params['Authorization'] = auth.authorization!;
  213. params['ContentType'] = auth.contentType!;
  214. final response = await http
  215. .put(
  216. Uri.parse(auth.storageUrl!),
  217. body: uint8List,
  218. headers: params,
  219. )
  220. .timeout(
  221. const Duration(seconds: 30),
  222. );
  223. if (response.statusCode == 200) {
  224. return auth.storageUrl!;
  225. }
  226. } catch (e) {
  227. PromptBox.toast('上传失败');
  228. logger.e("file upload error", e);
  229. return null;
  230. }
  231. return null;
  232. }
  233. ///文件上传(base64)
  234. Future<String?> uploadBase64File(String base64Str, String name) async {
  235. try {
  236. var buffer = base64.decode(base64Str);
  237. return uploadUint8List(buffer, name);
  238. } catch (e) {
  239. logger.e("file upload error", e);
  240. }
  241. return null;
  242. }
  243. ///文件上传(UInt8List)
  244. Future<String?> uploadUint8List(Uint8List buffer, String name,
  245. [bool? isRechristen]) async {
  246. try {
  247. var nameInfos = name.split('.');
  248. final auth = await getAuth(
  249. fileName: nameInfos.last,
  250. isRechristen: isRechristen,
  251. );
  252. Map<String, String> params = {};
  253. params['Authorization'] = auth.authorization!;
  254. params['ContentType'] = auth.contentType!;
  255. final response = await http
  256. .put(
  257. Uri.parse(auth.storageUrl!),
  258. body: buffer,
  259. headers: params,
  260. )
  261. .timeout(
  262. const Duration(seconds: 30),
  263. );
  264. if (response.statusCode == 200) {
  265. return auth.storageUrl;
  266. }
  267. } catch (e) {
  268. logger.e('StorageServiceExt uploadUint8List ex:$e');
  269. }
  270. return null;
  271. }
  272. }