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('上传图片'),
        ),
      ),
    );
  }
}
相关推荐
李恒-聆机智能专精数采1 小时前
从零开始了解数据采集(二十七)——什么IIOT平台
大数据·人工智能·云计算·制造·数据采集·数据可视化
GreatNXY4 小时前
【阿里云】阿里云 Ubuntu 服务器无法更新 systemd(Operation not permitted)的解决方法
服务器·阿里云·云计算
Lw老王要学习6 小时前
Linux架构篇、第五章git2.49.0部署与使用
linux·运维·git·云计算·it
亚林瓜子16 小时前
AWS EC2源代码安装valkey命令行客户端
redis·云计算·aws·cli·valkey
Johny_Zhao18 小时前
K8S+nginx+MYSQL+TOMCAT高可用架构企业自建网站
linux·网络·mysql·nginx·网络安全·信息安全·tomcat·云计算·shell·yum源·系统运维·itsm
大G哥1 天前
实战演练:用 AWS Lambda 和 API Gateway 构建你的第一个 Serverless API
云原生·serverless·云计算·gateway·aws
weixin_307779131 天前
使用FastAPI微服务在AWS EKS中构建上下文增强型AI问答系统
人工智能·python·云计算·fastapi·aws
是垚不是土2 天前
Kolla-Ansible搭建与扩容OpenStack私有云平台
linux·运维·服务器·云计算·ansible·openstack
同聘云2 天前
阿里云ddos云防护服务器有哪些功能?ddos防御手段有哪些??
服务器·阿里云·云计算·ddos
鸡鸭扣2 天前
DRF/Django+Vue项目线上部署:腾讯云+Centos7.6(github的SSH认证)
前端·vue.js·python·django·腾讯云·drf