Flutter阿里云OSS存储插件better_aliyun_oss的使用

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

Flutter阿里云OSS存储插件better_aliyun_oss的使用

better_aliyun_oss

A Simple Aliyun OSS Upload for Flutter.


安装与开始

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  better_aliyun_oss: ^0.0.8

2. 安装依赖

运行以下命令安装依赖:

$ flutter pub get

常规用法

以下是一个简单的示例,展示如何使用 better_aliyun_oss 插件进行文件上传。

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:better_aliyun_oss/better_aliyun_oss.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';

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

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

class _MyAppState extends State<MyApp> {
  late BetterAliyunOssClient ossClient;

  late StreamSubscription eventStreamSubscription;

  // 简单数据上传请求
  BetterAliyunOssClientRequest? simplePutRequest;

  [@override](/user/override)
  void initState() {
    super.initState();

    // 初始化 OSS 客户端
    ossClient = BetterAliyunOssClient(credentials);

    // 监听事件流
    eventStreamSubscription = ossClient.eventStream.listen((event) {
      print(event);
    });
  }

  [@override](/user/override)
  void dispose() {
    // 取消事件监听
    eventStreamSubscription.cancel();

    super.dispose();
  }

  // 获取临时文件路径
  Future<String> _getFilePath() async {
    final directory = await getTemporaryDirectory();
    return path.join(directory.path, "example.txt");
  }

  // 生成 OSS 凭证
  Future<BetterAliyunOssCredentials?> credentials() async {
    final credentials = {
      "SecurityToken": "",
      "AccessKeyId": "",
      "AccessKeySecret": "",
      "Expiration": "",
    };
    return BetterAliyunOssCredentials.fromMap(credentials);
  }

  // 简单上传文件
  void simpleUpload() async {
    // 创建一个示例文件
    final filePath = await _getFilePath();
    final file = File(filePath);
    await file.writeAsString("Hello OSS!");

    // 定义上传参数
    final objectFileName = Uuid().v1().replaceAll("-", "") + ".txt";
    final objectPath = "example/${DateTime.now().millisecondsSinceEpoch}/$objectFileName";

    // 执行上传
    simplePutRequest = ossClient.putObject(
      bucket: () async => "my-bucket",
      endpoint: () async => "oss-cn-hangzhou.aliyuncs.com",
      domain: () async => "https://domain.com",
      objectPath: objectPath,
      contentType: "text/plain",
      path: filePath,
    );

    print("简单数据上传请求 ID: ${simplePutRequest?.requestTaskId}");
  }

  // 取消简单上传
  void cancelSimpleUpload() {
    if (simplePutRequest != null) {
      ossClient.cancelPutObject(simplePutRequest!);
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('better_aliyun_oss 示例')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
            // 简单上传按钮
            ElevatedButton(
              onPressed: simpleUpload,
              child: Text('简单上传'),
            ),
            // 取消上传按钮
            ElevatedButton(
              onPressed: cancelSimpleUpload,
              child: Text('取消上传'),
            ),
          ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


better_aliyun_oss 是一个 Flutter 插件,用于在 Flutter 应用中与阿里云对象存储(OSS)进行交互。它提供了简单易用的 API,用于上传、下载和管理阿里云 OSS 中的文件。以下是如何使用 better_aliyun_oss 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  better_aliyun_oss: ^1.0.0  # 请使用最新版本

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

2. 初始化插件

在你的 Dart 代码中初始化 better_aliyun_oss 插件。你需要提供阿里云 OSS 的 accessKeyIdaccessKeySecretendpointbucketName

import 'package:better_aliyun_oss/better_aliyun_oss.dart';

void initOSS() {
  BetterAliyunOss.init(
    accessKeyId: 'your_access_key_id',
    accessKeySecret: 'your_access_key_secret',
    endpoint: 'your_endpoint', // 例如: 'https://oss-cn-hangzhou.aliyuncs.com'
    bucketName: 'your_bucket_name',
  );
}

3. 上传文件

使用 BetterAliyunOss.uploadFile 方法上传文件到阿里云 OSS。

void uploadFile() async {
  String filePath = '/path/to/your/file.txt';
  String ossPath = 'folder/file.txt'; // OSS 中的路径

  try {
    String url = await BetterAliyunOss.uploadFile(filePath, ossPath);
    print('File uploaded successfully. URL: $url');
  } catch (e) {
    print('Failed to upload file: $e');
  }
}

4. 下载文件

使用 BetterAliyunOss.downloadFile 方法从阿里云 OSS 下载文件。

void downloadFile() async {
  String ossPath = 'folder/file.txt'; // OSS 中的路径
  String savePath = '/path/to/save/file.txt'; // 本地保存路径

  try {
    await BetterAliyunOss.downloadFile(ossPath, savePath);
    print('File downloaded successfully.');
  } catch (e) {
    print('Failed to download file: $e');
  }
}

5. 删除文件

使用 BetterAliyunOss.deleteFile 方法从阿里云 OSS 删除文件。

void deleteFile() async {
  String ossPath = 'folder/file.txt'; // OSS 中的路径

  try {
    await BetterAliyunOss.deleteFile(ossPath);
    print('File deleted successfully.');
  } catch (e) {
    print('Failed to delete file: $e');
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!