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('上传图片'),
        ),
      ),
    );
  }
}
相关推荐
全云在线allcloudonline19 小时前
江苏阿里云代理商怎么选?现有服务点、南京节点与项目交付
阿里云·云计算·企业上云
全云在线allcloudonline21 小时前
湖北阿里云代理商怎么选?现有服务点、武汉节点与项目交付
阿里云·云计算·企业上云
全云在线allcloudonline1 天前
陕西阿里云代理商怎么选?现有服务点、西安节点与项目交付
阿里云·云计算·企业上云
搞科研的小刘选手1 天前
【哈尔滨信息工程学院主办】第五届信息经济、数据建模与云计算国际学术会议(ICIDC 2026)
云计算·数据建模·学术会议·会议推荐·信息经济
xywww1681 天前
Claude Opus 5 API 接入实战:国内项目上线前的网络、Key、限流和排错清单
大数据·linux·网络·数据库·云计算·aws
AOwhisky2 天前
Linux(CentOS)系统管理入门笔记(第十四期)——计划任务与进程调度管理:atcron 与 nicechrt
linux·运维·笔记·centos·云计算·进程调度·计划任务
冰封之寂2 天前
Docker 资源管理终极指南:CPU、内存与 IO 的精细化控制
linux·运维·服务器·docker·云计算
yiyeguzhou1003 天前
Load/Store 和 Register–memory 架构
性能优化·云计算
AOwhisky3 天前
Linux(CentOS)系统管理入门笔记(第十二期)——系统管理工具与软件包管理(上篇):Cockpit 与 RPM 包管理
linux·运维·笔记·centos·云计算
MGS浪疯3 天前
我用 WorkBuddy 做了一个能记住前文的 AI 小说编辑器
人工智能·编辑器·腾讯云·腾讯云ai代码助手·workbuddy开发者分享季·codebuddy开发者分享季