Blame view

lib/utils/aliyun_oss_util.dart 2.3 KB
795acc7e   Key   feat: aliyun oss ...
1
  import 'package:dio/dio.dart';
b15fde72   liangchengyou   feat:头像上传功能完善逻辑
2
  import 'package:flutter/cupertino.dart';
795acc7e   Key   feat: aliyun oss ...
3
4
5
6
7
8
9
10
11
12
13
14
15
  import 'package:flutter_oss_aliyun/flutter_oss_aliyun.dart';
  import 'package:wow_english/common/request/request_client.dart';
  import 'package:wow_english/models/aliyun_oss_upload_sts_entity.dart';
  import 'package:wow_english/utils/log_util.dart';
  
  /// 阿里云 oss 工具类,服务端给的鉴权一次有效
  /// 这个库的Client是个单例,如果并发使用请注意所调用的Client归属,Client.init会生成一个新的_instance
  class AliyunOssUtil {
    static Future<String> uploadFile(String filePath) async {
      // 取出文件名
      String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length);
      Log.d("待上传文件fileName: $fileName");
      // 获取鉴权信息
b15fde72   liangchengyou   feat:头像上传功能完善逻辑
16
17
18
19
20
21
      AliyunOssUploadStsEntity? stsEntity = await _getSts(fileName);
      if(stsEntity == null) {
        // todo 为空的情况抛出错误
        return '';
      }
      debugPrint('鉴权信息$stsEntity');
795acc7e   Key   feat: aliyun oss ...
22
23
24
25
26
27
28
29
      // 鉴权
      Client.init(
        ossEndpoint: stsEntity.endpoint,
        bucketName: stsEntity.bucket,
        authGetter: stsEntity.authGetter,
      );
  
      // 上传文件
68dd7ba8   liangchengyou   feat:首页主题颜色+已知问题修改
30
      await Client().putObjectFile(
795acc7e   Key   feat: aliyun oss ...
31
32
33
34
35
36
37
38
39
        filePath,
        fileKey: stsEntity.fileKey,
        option: PutRequestOption(
          onSendProgress: (count, total) {
            Log.d("send: count = $count, and total = $total");
          },
          onReceiveProgress: (count, total) {
            Log.d("receive: count = $count, and total = $total");
          },
e55bbdf3   Key   fixed: aliyun oss...
40
          aclModel: AclMode.publicRead,
795acc7e   Key   feat: aliyun oss ...
41
42
43
44
45
46
47
48
49
50
51
          callback: Callback(
            callbackUrl: stsEntity.callbackParam.callbackUrl,
            callbackBody: stsEntity.callbackParam.callbackBody,
            calbackBodyType: CalbackBodyType.json,
          ),
        ),
      );
      return '${stsEntity.host}/${stsEntity.fileKey}';
    }
  
    /// 获取鉴权信息
b15fde72   liangchengyou   feat:头像上传功能完善逻辑
52
53
54
    static Future<AliyunOssUploadStsEntity?> _getSts(String fileName) async {
      var result = await requestClient.get<AliyunOssUploadStsEntity>(Apis.aliyunOssSts, queryParameters: {'fileName': fileName});
      debugPrint('鉴权结果$result');
795acc7e   Key   feat: aliyun oss ...
55
56
57
58
59
60
61
62
63
64
65
66
67
68
      return result;
    }
  }
  
  extension StsExtension on AliyunOssUploadStsEntity {
    Auth authGetter() {
      return Auth(
        accessKey: accessKeyId,
        accessSecret: accessKeySecret,
        expire: expiration,
        secureToken: securityToken,
      );
    }
  }