Flutter Amazon S3与Cognito集成插件amazon_s3_cognito的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter Amazon S3与Cognito集成插件amazon_s3_cognito的使用

插件简介

amazon_s3_cognito是为Flutter编写的非官方Amazon S3插件,允许开发者轻松地将AWS Cognito和S3服务集成到他们的应用中。该插件由fäm properties维护。

使用方法

添加依赖

要在项目中使用此插件,请在pubspec.yaml文件中添加如下依赖:

dependencies:
  amazon_s3_cognito: '^0.7.9'

确保你的项目支持AndroidX。

示例代码

下面是一个完整的示例demo,展示了如何使用amazon_s3_cognito进行单个文件上传、多个文件上传以及删除文件的操作。

import 'dart:async';
import 'dart:collection';
import 'package:amazon_s3_cognito/amazon_s3_cognito.dart';
import 'package:amazon_s3_cognito/image_data.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  EventChannel _amazonS3Stream = EventChannel('amazon_s3_cognito_images_upload_steam');
  StreamSubscription? uploadListenerSubscription;

  List<ImageData> filesToUpload = [];

  @override
  void initState() {
    super.initState();
    _listenToFileUpload();
  }

  void _listenToFileUpload() {
    //监听文件上传进度
    uploadListenerSubscription =
        _amazonS3Stream.receiveBroadcastStream().listen((event) {
      LinkedHashMap<Object?, Object?> map = event;
      print(map);
      ImageData imageData = ImageData.fromMap(map);
      //根据返回的对象更新UI
    });
  }

  Future<void> uploadMultipleFileUploads() async {
    String bucketName = "test";
    String cognitoPoolId = "your pool id";
    String bucketRegion = "imageUploadRegion";
    String bucketSubRegion = "Sub region of bucket";

    //可选参数:文件上传的文件夹
    String fileUploadFolder = "folder inside bucket where we want file to be uploaded";

    //模拟三个相同文件的上传
    for (int i = 0; i < 3; i++) {
      String filePath = ""; //待上传文件路径
      ImageData imageData = ImageData("uniqueFileName$i", filePath,
          uniqueId: "uniqueIdToTrackImage$i", imageUploadFolder: fileUploadFolder);
      filesToUpload.add(imageData);
    }

    //是否需要进度更新,仅iOS适用的大文件分段上传设置
    await AmazonS3Cognito.uploadImages(bucketName, cognitoPoolId, bucketRegion,
        bucketSubRegion, filesToUpload, false);
  }

  Future<void> uploadSingleImage() async {
    String bucketName = "test";
    String cognitoPoolId = "your pool id";
    String bucketRegion = "imageUploadRegion";
    String bucketSubRegion = "Sub region of bucket";

    //可选参数:文件上传的文件夹
    String fileUploadFolder = "folder inside bucket where we want file to be uploaded";

    String filePath = ""; //待上传文件路径
    ImageData imageData = ImageData("uniqueFileName", filePath,
        uniqueId: "uniqueIdToTrackImage", imageUploadFolder: fileUploadFolder);

    //结果为亚马逊S3 URL或失败原因
    String? result = await AmazonS3Cognito.upload(
        bucketName, cognitoPoolId, bucketRegion, bucketSubRegion, imageData,
        needMultipartUpload: true);
    //根据上传成功与否更新UI
    print(result);
  }

  Future<void> deleteImage() async {
    String cognitoPoolId = "your pool id";
    String bucketRegion = "imageUploadRegion";
    String bucketSubRegion = "Sub region of bucket";

    //可选参数:文件所在文件夹
    String bucketName = "test";
    String fileUploadFolder = "101/";
    String fileName = "abc.jpg";

    String? result = await AmazonS3Cognito.delete(bucketName, cognitoPoolId,
        fileName, fileUploadFolder, bucketRegion, bucketSubRegion);

    if (result != null) {
      print(result);
    }
  }

  @override
  void dispose() {
    super.dispose();
    uploadListenerSubscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(onPressed: uploadSingleImage, child: Text("上传单个文件")),
              ElevatedButton(onPressed: uploadMultipleFileUploads, child: Text("上传多个文件")),
              ElevatedButton(onPressed: deleteImage, child: Text("删除文件"))
            ],
          ),
        ),
      ),
    );
  }
}

安装指南

Android配置

AndroidManifest.xml中注册TransferService:

<application>
  <service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android:enabled="true" />
</application>

iOS配置

AppDelegate.swift中添加以下方法以处理后台URL会话事件:

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
  AWSS3TransferUtility.interceptApplication(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler)
}

更多关于iOS后台传输的信息可以参考官方文档

注意事项

  • 在bucket名称中只发送bucket名称。如果你希望将文件上传到bucket中的某个子文件夹,请不要在bucket名称中包含子文件夹,而是在ImageData.imageUploadFolder中指定。
  • 对于iOS平台,当上传文件非常大以至于可能超过1小时时,设置needMultipartUploadtrue

通过以上步骤,你就可以在Flutter应用中集成Amazon S3与Cognito了。如果有任何问题或需要进一步的帮助,请随时提问!


更多关于Flutter Amazon S3与Cognito集成插件amazon_s3_cognito的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Amazon S3与Cognito集成插件amazon_s3_cognito的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成并使用amazon_s3_cognito插件来与Amazon S3和Amazon Cognito进行交互的代码示例。这个插件通常用于身份验证(通过Cognito)和文件上传/下载(通过S3)。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加amazon_s3_cognito依赖:

dependencies:
  flutter:
    sdk: flutter
  amazon_s3_cognito: ^x.y.z  # 替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Amazon Cognito

你需要配置Amazon Cognito的用户池,并获取必要的配置信息,如用户池ID、客户端ID、区域等。这些信息将用于初始化Cognito用户会话。

3. 初始化Cognito和S3

在你的Flutter应用中,初始化Cognito和S3客户端。以下是一个简单的初始化示例:

import 'package:flutter/material.dart';
import 'package:amazon_s3_cognito/amazon_s3_cognito.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Amazon S3 & Cognito Integration'),
        ),
        body: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final AmazonS3Cognito _amazonS3Cognito = AmazonS3Cognito();

  @override
  void initState() {
    super.initState();
    _configureCognito();
  }

  Future<void> _configureCognito() async {
    try {
      // 配置Cognito
      String poolId = 'your-cognito-user-pool-id';
      String clientId = 'your-cognito-client-id';
      String region = 'your-aws-region';

      await _amazonS3Cognito.configure(poolId, clientId, region);
      
      // 初始化用户会话(通常你需要用户登录信息)
      // 这里我们假设已经有一个有效的用户会话
      // 你可以使用 AmazonCognitoAuth.federatedSignIn 或 AmazonCognitoAuth.signIn 方法
      // 来获取用户的会话信息
      
      // 示例:用户登录(这里你需要实际的用户凭证)
      // var authDetails = AmazonCognitoAuthUser(
      //   username: 'user@example.com',
      //   password: 'password',
      // );
      // await _amazonS3Cognito.amazonCognitoAuth.signIn(authDetails);
      
      // 注意:上面的登录代码只是一个示例,你需要根据实际的用户凭证来登录
      
      // 一旦登录成功,你就可以使用S3客户端了
      print('Cognito configured successfully');
    } catch (e) {
      print('Error configuring Cognito: $e');
    }
  }

  // 示例:上传文件到S3
  Future<void> _uploadFileToS3() async {
    try {
      String bucketName = 'your-s3-bucket-name';
      String keyName = 'path/to/your/file.ext';
      String filePath = '/path/to/local/file.ext';

      var uploadFileRequest = AmazonS3UploadFileRequest(
        bucket: bucketName,
        key: keyName,
        filePath: filePath,
        contentType: 'application/octet-stream',  // 根据文件类型设置
      );

      var result = await _amazonS3Cognito.amazonS3.uploadFile(uploadFileRequest);
      print('File uploaded successfully: ${result.location}');
    } catch (e) {
      print('Error uploading file: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('Amazon S3 & Cognito Integration Example'),
          ElevatedButton(
            onPressed: _uploadFileToS3,
            child: Text('Upload File to S3'),
          ),
        ],
      ),
    );
  }
}

注意事项

  1. 安全性:不要在代码中硬编码敏感信息(如用户凭证)。使用环境变量或安全的密钥管理服务。
  2. 错误处理:上述代码示例中的错误处理较为简单,实际应用中应添加更详细的错误处理和用户反馈。
  3. 依赖版本:确保你使用的是最新版本的amazon_s3_cognito插件,并查看其官方文档以获取最新的配置和使用方法。

以上代码展示了如何在Flutter应用中集成amazon_s3_cognito插件,并初始化Cognito和S3客户端,以及上传文件到S3的基本流程。

回到顶部