Flutter AWS存储服务插件aws_storage_service的使用

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

Flutter AWS存储服务插件aws_storage_service的使用

aws_storage_service 是一个用于在 Dart 和 Flutter 应用程序中处理文件上传、多部分上传和下载的简单包。以下是该插件的使用示例和详细说明。

示例代码

文件上传

import 'dart:io';

import 'package:path/path.dart' as p;

import 'package:aws_storage_service/src/aws_storage_service.dart';

AwsCredentialsConfig credentialsConfig = AwsCredentialsConfig(
  accessKey: 'YOURACCESSKEY', // 这是一个测试访问密钥
  bucketName: 'testbucket', // 桶名称
  region: 'us-west-2', // 您的 AWS 桶所在区域
  secretKey: 'YOURAWSSECRETKEY', // 您的密钥
);

Future testFileUpload() async {
  File file = File(p.join(Directory.current.path, 'web.pdf'));

  print(file.lengthSync());

  UploadTaskConfig config = UploadTaskConfig(
    credentailsConfig: credentialsConfig,
    url: 'file/web23.pdf',
    uploadType: UploadType.file,
    file: file,
  );

  UploadFile uploadFile = UploadFile(config: config);

  uploadFile.uploadProgress.listen((event) {
    print('${event[0]}/ ${event[1]}');
  });

  await uploadFile.upload().then((value) {
    print(value);
    uploadFile.dispose();
  });
}

多部分上传

Future testMultipartUpload() async {
  String imageName = 'test.mp4';
  File file = File(p.join(Directory.current.path, 'test_files', imageName));

  MultipartUploadConfig config = MultipartUploadConfig(
    file: file,
    url: 'file/f$imageName',
    credentailsConfig: credentialsConfig,
  );

  MultipartFileUpload multipartFileUpload = MultipartFileUpload(
    config: config,
    onError: (error, list, s) {
      print('An error occurred $error');
    },
    onVersionIdCreated: (versionId) => print('version id created $versionId'),
    onPartUploadComplete: (etagList, versionId) => print(
        'Part upload completed ---> etagList is $etagList and versionId is $versionId'),
    onUploadComplete: (etagList, versionId) => print(
        'Part upload completed ---> etagList is $etagList and versionId is $versionId'),
  );

  multipartFileUpload.uploadCompletedState.listen((event) {
    // Event is a boolean. This is true when the file upload is done
    print('Upload State $event');
  });

  multipartFileUpload.uploadProgress.listen((event) {
    print('Upload progress \n${event[0]} / ${event[1]}');
  });

  bool preparingSuccessful = await multipartFileUpload.prepareMultipartRequest();

  if (preparingSuccessful) {
    await multipartFileUpload.upload();
  }
}

恢复多部分上传

Future testResumeMultipartUpload() async {
  String imageName = 'test.mp4'; // 要上传的文件名
  File file = File(p.join(Directory.current.path, 'test_files', imageName));

  // EtagLists 是已上传的 Etag 列表。
  // 对于每次上传到 AWS 的块,都会返回一个 Etag ID。
  // 包含了一个方法,每次成功上传一个块时都会返回所有已上传的 Etag 列表。
  final eTagLists = [
    [2, "1ee28a7ac06786aff26d47298674c847"],
    [1, "18cc73a82389202aa085ee5751666726"],
    [4, "bf41ee73393dbfa1a5327fbb50aff054"],
    [5, "2848ec759573e3c5f6cadf1145e9efd9"]
  ];

  // 版本 ID 是在上传开始时分配给此上传的唯一 ID。
  final versionIdOrUploadId =
      'Zm9F2QhTuSZQHhnw1O8sThNk9fZ71lAUf20oTUQ11NrUaQy5DUwZ8oZ7fXuxCZywyY8mwUqsa54M3yg1S2QFIWGV.kv_QiMAxGlNHC55OAzBlDIusdJJ2jLF7qaQk9yg';

  // 创建配置对象。
  MultipartUploadConfig config = MultipartUploadConfig(
    credentailsConfig: credentialsConfig,
    file: file,
    url: 'file/f$imageName',
    resumeMultipart: true,
    versionId: versionIdOrUploadId,
    etagsLists: eTagLists,
  );

  MultipartFileUpload multipartFileUpload = MultipartFileUpload(
    config: config,
    onError: (error, list, s) {
      print('An error occurred $error');
    },
    onVersionIdCreated: (versionId) => print('version id created $versionId'),
    onPartUploadComplete: (etagList, versionId) => print(
        'Part upload completed ---> etagList is $etagList and versionId is $versionId'),
    onUploadComplete: (etagList, versionId) => print(
        'Part upload completed ---> etagList is $etagList and versionId is $versionId'),
  );

  multipartFileUpload.uploadCompletedState.listen((event) {
    // Event is a boolean. This is true when the file upload is done
    print('Upload State $event');
  });

  multipartFileUpload.uploadProgress.listen((event) {
    print('Upload progress \n${event[0]} / ${event[1]}');
  });

  bool preparingSuccessful = await multipartFileUpload.prepareMultipartRequest();

  if (preparingSuccessful) {
    await multipartFileUpload.upload();
  }
}

下载文件

Future testDownload() async {
  // 新建一个下载任务
  String filePath = p.join(Directory.current.path, 'test_download.mp4');

  String fileUrl = 'file/ftest.mp4'; // 文件在桶中的 URL

  DownloadFileConfig config = DownloadFileConfig(
    credentailsConfig: credentialsConfig,
    url: fileUrl,
    downloadPath: filePath,
  );

  DownloadFile downloadFile = DownloadFile(
    config: config,
    onRecieveProgress: ((totalDownloaded, totalSize) =>
        print('Upload Status Callback ===> $totalDownloaded/$totalSize')),
    errorCallback: (errorMessage, statusCode) =>
        print('An error occurred $errorMessage'),
  );

  bool prepSuccessful = await downloadFile.prepareDownload();
  print('The download was prepared Successfully $prepSuccessful');

  downloadFile.downloadProgress.listen((event) {
    print('Upload Status Stream ===> ${event[0]}/${event[1]}');
  });

  if (prepSuccessful) {
    await downloadFile.download().then((value) {
      downloadFile.dispose();
    });
  }
}

恢复下载

Future testResumeDownload() async {
  // 这个测试上传文件
  String filePath = p.join(Directory.current.path, 'test_download.mp4');

  String fileUrl = 'file/ftest.mp4'; // 文件在桶中的 URL

  // 创建一个下载配置
  // 下载配置包含了下载器需要的所有配置信息来下载文件
  DownloadFileConfig config = DownloadFileConfig(
    credentailsConfig: credentialsConfig,
    url: fileUrl,
    resumeDownload: true, // 如果要恢复下载,则设置为 true
    downloadPath: filePath, // 要恢复的文件路径
  );

  DownloadFile downloadFile = DownloadFile(
    config: config,
    onRecieveProgress: ((totalDownloaded, totalSize) =>
        print('Upload Status Callback ===> $totalDownloaded/$totalSize')),
    errorCallback: (errorMessage, statusCode) =>
        print('An error occurred $errorMessage'),
  ); // 创建一个下载文件实例

  bool prepSuccessful = await downloadFile.prepareDownload();
  print('The download was prepared Successfully $prepSuccessful');

  downloadFile.downloadProgress.listen((event) {
    // 您可以监听下载进度
    print('Upload Status Stream ===> ${event[0]}/${event[1]}');
  });

  if (prepSuccessful) {
    await downloadFile.download().then((value) {
      downloadFile.dispose();
    });
  }
}

更多关于Flutter AWS存储服务插件aws_storage_service的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter AWS存储服务插件aws_storage_service的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用aws_storage_service插件的示例代码。请注意,这只是一个基本示例,具体实现可能需要根据您的项目需求进行调整。此外,aws_storage_service并不是AWS官方提供的Flutter插件,这里假设它是一个自定义的或第三方插件,用于与AWS存储服务(如S3)进行交互。

首先,确保您已经在pubspec.yaml文件中添加了aws_storage_service依赖项:

dependencies:
  flutter:
    sdk: flutter
  aws_storage_service: ^x.y.z  # 请替换为实际版本号

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

接下来,您需要在Flutter项目中配置AWS凭证。通常,这涉及到设置AWS的Access Key ID、Secret Access Key、Region等。这些信息可以通过环境变量或配置文件进行管理,但为了简化示例,这里直接在代码中硬编码(实际项目中应避免这样做)。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter AWS Storage Service Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  final AwsStorageService awsStorageService = AwsStorageService(
    accessKeyId: 'YOUR_ACCESS_KEY_ID',
    secretAccessKey: 'YOUR_SECRET_ACCESS_KEY',
    region: 'YOUR_REGION',
    bucketName: 'YOUR_BUCKET_NAME',
  );

  String uploadStatus = '';

  void uploadFile() async {
    setState(() {
      uploadStatus = 'Uploading...';
    });

    try {
      var file = File('/path/to/your/file.txt');
      var uploadResult = await awsStorageService.uploadFile(file, 'file.txt');
      
      setState(() {
        uploadStatus = 'Upload successful: ${uploadResult.url}';
      });
    } catch (e) {
      setState(() {
        uploadStatus = 'Upload failed: ${e.message}';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter AWS Storage Service Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(uploadStatus),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: uploadFile,
              child: Text('Upload File'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,它包含一个按钮,用于将本地文件上传到AWS S3存储桶。AwsStorageService是一个假设的类,它封装了与AWS S3交互的逻辑。您需要根据实际的aws_storage_service插件API调整代码。

请注意,uploadFile方法中的文件路径(/path/to/your/file.txt)应该替换为您实际想要上传的文件路径。

此外,由于直接在代码中硬编码AWS凭证是不安全的,建议采用更安全的方法,如使用AWS Amplify、AWS Cognito进行身份验证,或使用环境变量和配置文件来管理敏感信息。

最后,确保您已经正确配置了AWS S3存储桶的权限,以便您的Flutter应用能够成功上传文件。

回到顶部