Flutter腾讯云COS存储插件fluent_qcloud_cos的使用

Flutter腾讯云COS存储插件fluent_qcloud_cos的使用

fluent_qcloud_cos

一个纯Dart实现的腾讯云对象存储的包。

Features

  • 简单文件上传
  • 分块上传(断点续传).

Usage

以下是一个完整的示例,展示如何使用fluent_qcloud_cos插件进行文件上传:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  [@override](/user/override)
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final String largeFilePath = "path/to/your/large/file"; // 替换为你的大文件路径
  final String bucketName = "your-bucket-name"; // 替换为你的桶名称
  final String secretId = "your-secret-id"; // 替换为你的Secret ID
  final String secretKey = "your-secret-key"; // 替换为你的Secret Key
  final String region = "your-region"; // 替换为你的区域

  void uploadFile() {
    final handler = ObjectStoragePutObjectEventHandler(taskId: "putObjectSimple");

    // 监听上传失败事件
    handler.onFailed = (event) {
      print("上传失败: ${event.errorMessage ?? "未知错误"}");
    };

    // 监听上传成功事件
    handler.onSuccess = (event) {
      print("上传成功");
    };

    // 监听上传进度事件
    handler.onProgress = (event) {
      print("${event.currentSize}/${event.totalSize}");
    };

    // 异步上传文件,注意不要使用await关键字
    FluentQCloudCos.putObject(
      ObjectStoragePutObjectRequest(
        taskId: "putObjectFileSizeMoreThan20M",
        filePath: largeFilePath,
        bucketName: bucketName,
        objectName: "file-small.jpg", // 替换为你想要保存的文件名
        accessKeyId: secretId,
        accessKeySecret: secretKey,
        securityToken: "",
        expiredTime:
            DateTime.now().add(const Duration(days: 50)).millisecondsSinceEpoch,
        region: region,
      ),
      handler: handler,
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("腾讯云COS上传示例"),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: uploadFile,
          child: Text("开始上传"),
        ),
      ),
    );
  }
}
1 回复

更多关于Flutter腾讯云COS存储插件fluent_qcloud_cos的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


fluent_qcloud_cos 是一个用于在 Flutter 应用中集成腾讯云对象存储(COS)的插件。它提供了简单易用的 API,方便开发者上传、下载、删除和管理存储在腾讯云 COS 中的文件。

1. 安装插件

首先,你需要在 pubspec.yaml 文件中添加 fluent_qcloud_cos 依赖:

dependencies:
  flutter:
    sdk: flutter
  fluent_qcloud_cos: ^0.0.1  # 请检查最新版本

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

2. 初始化插件

在使用插件之前,你需要初始化它。通常你可以在 main.dart 中进行初始化:

import 'package:fluent_qcloud_cos/fluent_qcloud_cos.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化腾讯云 COS
  await FluentQcloudCos.init(
    appId: 'your_app_id',
    secretId: 'your_secret_id',
    secretKey: 'your_secret_key',
    region: 'your_region',  // 例如:ap-guangzhou
    bucket: 'your_bucket_name',
  );
  
  runApp(MyApp());
}

3. 上传文件

你可以使用 FluentQcloudCos.uploadFile 方法来上传文件:

import 'package:fluent_qcloud_cos/fluent_qcloud_cos.dart';

Future<void> uploadFile() async {
  try {
    final filePath = '/path/to/your/file.txt';
    final cosPath = 'uploads/file.txt';  // COS 中的路径

    final response = await FluentQcloudCos.uploadFile(
      filePath: filePath,
      cosPath: cosPath,
    );

    print('File uploaded successfully: ${response.url}');
  } catch (e) {
    print('Failed to upload file: $e');
  }
}

4. 下载文件

你可以使用 FluentQcloudCos.downloadFile 方法来下载文件:

import 'package:fluent_qcloud_cos/fluent_qcloud_cos.dart';

Future<void> downloadFile() async {
  try {
    final cosPath = 'uploads/file.txt';  // COS 中的路径
    final savePath = '/path/to/save/file.txt';  // 本地保存路径

    await FluentQcloudCos.downloadFile(
      cosPath: cosPath,
      savePath: savePath,
    );

    print('File downloaded successfully');
  } catch (e) {
    print('Failed to download file: $e');
  }
}

5. 删除文件

你可以使用 FluentQcloudCos.deleteFile 方法来删除文件:

import 'package:fluent_qcloud_cos/fluent_qcloud_cos.dart';

Future<void> deleteFile() async {
  try {
    final cosPath = 'uploads/file.txt';  // COS 中的路径

    await FluentQcloudCos.deleteFile(
      cosPath: cosPath,
    );

    print('File deleted successfully');
  } catch (e) {
    print('Failed to delete file: $e');
  }
}

6. 获取文件列表

你可以使用 FluentQcloudCos.listFiles 方法来获取文件列表:

import 'package:fluent_qcloud_cos/fluent_qcloud_cos.dart';

Future<void> listFiles() async {
  try {
    final prefix = 'uploads/';  // 文件前缀

    final files = await FluentQcloudCos.listFiles(
      prefix: prefix,
    );

    print('Files: $files');
  } catch (e) {
    print('Failed to list files: $e');
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!