我尝试使用“aws_s3_upload”包将文件从我的 Flutter 应用程序上传到 AWS S3 存储桶,但我不断遇到“管道损坏”错误。这是我的代码的相关部分:
Future<String> uploadImage_to_S3(
File image, User? currentUser, String whichFolderToPut) async {
// image = await _compressImage(image);
try {
// Create a unique filename for the image
String fileName =
'${currentUser?.uid}_${currentUser?.email}_${DateTime.now().millisecondsSinceEpoch.toString()}${path.extension(image.path)}';
// AWS S3 configuration
final awsAccessKey = "xxxxxxxxxxxx";
final awsSecretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
final bucketName = "alliancenetwork-production";
final region = "ap-south-1";
// Upload the image to S3
final result = await AwsS3.uploadFile(
accessKey: awsAccessKey,
secretKey: awsSecretKey,
file: image,
bucket: bucketName,
region: region,
key: "$whichFolderToPut/$fileName",
metadata: {
'Content-Type': 'image/${path.extension(image.path).substring(1)}'
},
);
if (result != null) {
// The result is the URL of the uploaded file
return result;
} else {
throw Exception('Failed to upload image to S3');
}
} catch (e) {
// Handle any errors that occur during the upload
print('Failed to upload image: $e');
return 'error: image upload to S3 failed';
}
}
我收到的错误是:
Failed to upload to AWS, with exception:
Broken pipe
检查了互联网连接,看起来稳定。 验证 AWS 凭证和 S3 存储桶策略以确保它们允许上传。 尝试增加请求的超时时间。 确保文件不太大并且可以正确读取。 记录了更详细的错误信息。
`aws_s3_api: ^2.0.0` worker for me
示例:
final s3Client = S3(
region: region,
credentials: AwsClientCredentials(
accessKey: credentials.accessKeyId!,
secretKey: credentials.secretAccessKey!,
sessionToken: credentials.sessionToken));
try {
final contentType = await FileUtil.getFileContentType(filePath);
final body = await File(filePath).readAsBytes();
final objectResponse = await s3Client.putObject(
bucket: "MyBucketW5",
key: "image.jpeg",
body: body,
contentType: contentType);
return filePath;
} catch (e) {
print('S3:::PutObject: $key failed, reason: $e');
rethrow;
}