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('上传图片'),
        ),
      ),
    );
  }
}
相关推荐
数字游民952715 分钟前
网站备案全流程回放(腾讯云)
人工智能·git·github·腾讯云·网站备案·waytoopc
CodeCaptain1 小时前
阿里云ECS上配置Nginx的反向代理
nginx·阿里云·云计算
有谁看见我的剑了?9 小时前
VMware OVF Tool 工具安装学习
云计算
盛夏52021 小时前
Docker容器化部署SpringBoot+Vue项目:从零到一在阿里云宝塔面板的实践指南
阿里云·docker·云计算
拔剑纵狂歌1 天前
helm-cli安装资源时序报错问题问题
后端·docker·云原生·容器·golang·kubernetes·腾讯云
狐571 天前
2026-01-10-云计算问答题部分整理-期末复习
云计算·期末复习
2401_861277551 天前
中国电信星辰AI大模型有哪些主要功能
人工智能·云计算·软件工程·语音识别
程序员雄杰1 天前
腾讯云轻量应用服务器mac中ssh免密登录到服务器
macos·ssh·腾讯云
Akamai中国2 天前
基准测试:Akamai云上的NVIDIA RTX Pro 6000 Blackwell
人工智能·云计算·云服务·云存储
oMcLin2 天前
如何在 Ubuntu 22.04 LTS 上部署并优化 OpenStack 云计算平台,实现多租户虚拟化与弹性伸缩?
ubuntu·云计算·openstack