flutter直接上传文件到阿里云oss
    		       		warning:
    		            这篇文章距离上次修改已过431天,其中的内容可能已经有所变动。
    		        
        		                
                在Flutter中直接上传文件到阿里云OSS,你可以使用阿里云提供的Flutter插件或者使用http包来实现。以下是使用http包实现的示例代码:
首先,你需要在阿里云OSS控制台获取你的accessKeyId、accessKeySecret、bucket(桶名)、endpoint(地域节点)等信息。
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;
 
Future<void> uploadToOSS(String accessKeyId, String accessKeySecret,
    String bucket, String endpoint, String filePath) async {
  final fileName = path.basename(filePath);
  final String policy = '你的签名政策';
  final String signature = '你的签名结果';
 
  final file = await http.MultipartFile.fromPath('file', filePath);
  final request = http.MultipartRequest('POST', Uri.parse('https://$bucket.$endpoint'))
    ..fields['key'] = fileName
    ..fields['policy'] = policy
    ..fields['OSSAccessKeyId'] = accessKeyId
    ..fields['signature'] = signature
    ..files.add(file);
 
  try {
    final response = await request.send();
    if (response.statusCode == 204) {
      print('File uploaded successfully.');
    } else {
      print('Upload failed, status code: ${response.statusCode}.');
    }
  } catch (e) {
    print('Upload error: $e');
  }
}
 
// 使用示例
void main() async {
  final accessKeyId = '你的accessKeyId';
  final accessKeySecret = '你的accessKeySecret';
  final bucket = '你的bucket';
  final endpoint = '你的endpoint';
  final filePath = '你的文件路径';
 
  await uploadToOSS(accessKeyId, accessKeySecret, bucket, endpoint, filePath);
}注意:你需要自己生成签名政策和签名结果,阿里云提供了对应的SDK来帮助你生成这些值。
这个示例代码中,uploadToOSS函数负责上传文件到OSS,你需要将相应的配置信息填入,并调用该函数。
如果你想要使用更简便的方法,可以考虑使用阿里云官方提供的Flutter插件,但是目前没有官方插件,你可能需要等待或自己实现。如果官方插件可用,使用会类似于下面的代码:
import 'package:aliyun_oss_flutter/aliyun_oss_flutter.dart';
 
// 使用示例
void main() async {
  final ossClient = OSSClient(
    endpoint: '你的endpoint',
    bucket: '你的bucket',
    accessKeyId: '你的accessKeyId',
    accessKeySecret: '你的accessKeySecret',
  );
 
  final filePath = '你的文件路径';
  final fileName = '你想要的文件名';
 
  try {
    final result = await ossClient.put('put', filePath, fileName);
    print('File uploaded to OSS with key: ${result.key}');
  } catch (e) {
    print('Upload error: $e');
  }
}请注意,这个插件代码示例是假定插件已经存在且发布在pub.dev上。如果实际情况中插件不存在,你需要自己实现或等待阿里云官方发布。
评论已关闭