首先配置文件添加 flutter_cos: ^0.0.3
添加COS配置
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 HeaderMap<String, String> headers = _createAuthorizationHeader(file);// 发起 PUT 请求将文件上传到COSvar 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 的逻辑,目前返回简化的 headersreturn {'Content-Type': 'application/octet-stream','Authorization':'Your_Authorization_String', // Replace with your actual Auth string computation'x-cos-security-token': '', // 如果使用临时密钥,则需提供};}
}
采用方法调用然后上传
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: '', // 这里填你实际的 appidregion: '', // 这里是你的 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');}}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text('上传图片到腾讯云 COS'),),body: Center(child: ElevatedButton(onPressed: uploadImageToCos,child: const Text('上传图片'),),),);}
}