flutter中采用腾讯云COS进行图片存储

首先配置文件添加 flutter_cos: ^0.0.3

添加COS配置

Dart 复制代码
import 'dart:io';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';

class CosConfig {
  final String appid;
  final String region;
  final String bucket;

  CosConfig({required this.appid, required this.region, required this.bucket});
}

class CosClient {
  final String secretId;
  final String secretKey;
  final CosConfig config;

  CosClient(
      {required this.secretId, required this.secretKey, required this.config});

  Future<Map<String, dynamic>?> putObject(
      {required String key, required File file}) async {
    final uri = Uri.parse(
        'https://${config.bucket}.cos.${config.region}.myqcloud.com/$key');

    // 准备 Authorization Header
    Map<String, String> headers = _createAuthorizationHeader(file);

    // 发起 PUT 请求将文件上传到COS
    var request = http.Request('PUT', uri)
      ..headers.addAll(headers)
      ..bodyBytes = await file.readAsBytes();

    http.StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      print('Upload success!');
      return {
        'url': 'https://${config.bucket}.cos.${config.region}.myqcloud.com/$key'
      };
    } else {
      print('Failed with status code: ${response.statusCode}.');
      return null;
    }
  }

  Map<String, String> _createAuthorizationHeader(File file) {
    // 这里应包含计算 Authorization 的逻辑,目前返回简化的 headers
    return {
      'Content-Type': 'application/octet-stream',
      'Authorization':
          'Your_Authorization_String', // Replace with your actual Auth string computation
      'x-cos-security-token': '', // 如果使用临时密钥,则需提供
    };
  }
}

采用方法调用然后上传

Dart 复制代码
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:aurio/utils/CosConfig.dart'; // 请确保这个库提供所需的CosClient和CosConfig类

class ImageUploadExample extends StatefulWidget {
  const ImageUploadExample({super.key});

  @override
  _UploadImageToCosState createState() => _UploadImageToCosState();
}

class _UploadImageToCosState extends State<ImageUploadExample> {
  final ImagePicker _picker = ImagePicker();

  Future<void> uploadImageToCos() async {
    print('开始选择图片');
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);

    if (image == null) {
      print('未选择图片');
      return;
    }

    print('图片选择成功: ${image.path}');
    File imageFile = File(image.path);

    // 创建配置
    var config = CosConfig(
      appid: '', // 这里填你实际的 appid
      region: '', // 这里是你的 COS 服务区域
      bucket: '', // 这里是你的桶名称
    );

    print('配置创建完毕');

    // 创建 client 实例
    var client = CosClient(
      secretId: '', // 实际使用时请勿硬编码密钥信息
      secretKey: '', // 上线时务必使用安全方案储存和使用密钥
      config: config,
    );

    print('COS客户端创建成功,开始上传图片');

    // 上传图片
    var res = await client.putObject(
      key: '', // 指定文件存储在COS的路径
      file: imageFile,
    );

    if (res == null) {
      print('上传未返回结果');
      return;
    }

    if (res['url'] != null) {
      print('上传成功,图片 URL: ${res['url']}');
      // 可以在这里更新 UI 或执行其他逻辑,比如保存 URL 到服务器
    } else {
      print('上传失败,返回结果:$res');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('上传图片到腾讯云 COS'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: uploadImageToCos,
          child: const Text('上传图片'),
        ),
      ),
    );
  }
}
相关推荐
容器魔方5 小时前
Volcano v1.16 发布:新增 NamespaceQueue 与 fairshare,拓展 HyperNode 生态
人工智能·云原生·容器·华为云·云计算
hz567895 小时前
本地部署视频会议系统软件功能有哪些?会议预约、权限分配与协作能力详解
安全·云计算·实时音视频·信息与通信·远程工作
GPU实战笔记8 小时前
A100 按量实例转长期计费前,需要确认哪些条件?
云计算·a100·按量计费·实例生命周期·gpu实例
无风听海12 小时前
AWS CLI的profile
云计算·aws
翼龙云_cloud1 天前
亚马逊云服务器服务代理商:Bedrock 实践经验 Serverless 架构下的 AI 自动化落地
服务器·架构·serverless·云计算·aws
GPU实战笔记1 天前
实例节点选择:创建入口与运行时稳定性的边界
云计算·a100·gpu 实例·节点选择·工作流验证
mengge.cloud1 天前
1019Namespace ,Contexts ,Kubernetes Pod
运维·服务器·网络·云原生·容器·kubernetes·云计算
云老大-阿里云国际站代理商1 天前
网站遇到恶意爬虫和CC攻击,阿里云国际站WAF与Bot管理怎么搭配
爬虫·阿里云·云计算
着迷不白2 天前
生产环境标准的Linux系统安装到服务器
linux·云计算
Geek-Chow2 天前
01 · Why AWS Lambda: Idle Cost, Capacity Planning and Risky In-Place Deploys
云计算