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('上传图片'),
        ),
      ),
    );
  }
}
相关推荐
知之则吱吱27 分钟前
亚马逊AWS云服务器高效使用指南:最大限度降低成本的实战策略
服务器·云计算·aws
tuan_zhang14 小时前
第七章:未名湖畔的樱花网关
程序人生·云计算
weixin_4180076014 小时前
MQTTX连接阿里云的物联网配置
物联网·阿里云·云计算
BOB-wangbaohai14 小时前
阿里云ACP云计算备考笔记 (4)——企业应用服务
阿里云·云计算·云监控·云解析·云cdn·sls日志服务
亚林瓜子19 小时前
AWS API Gateway配置日志
云计算·gateway·aws·log·cloudwatch
^Rocky1 天前
uniapp 对接腾讯云IM群公告功能
uni-app·腾讯云
CRMEB定制开发1 天前
CRMEB 中 PHP 快递查询扩展实现:涵盖一号通、阿里云、腾讯云
阿里云·php·腾讯云·商城系统·商城源码
家庭云计算专家1 天前
飞牛云一键设置动态域名+ipv6内网直通访问内网的ssh服务-家庭云计算专家
运维·云计算·ssh·nextcloud·ddns·动态域名解析
waving-black1 天前
利用frp和腾讯云服务器将内网暴露至外网(内网穿透)
linux·服务器·腾讯云·frp·内网穿透
Johny_Zhao1 天前
华为MAAS、阿里云PAI、亚马逊AWS SageMaker、微软Azure ML各大模型深度分析对比
linux·人工智能·ai·信息安全·云计算·系统运维