flutteramazon-web-servicesamazon-s3

Flutter: "Broken pipe" Error when uploading files to AWS S3 using "aws_s3_upload" Package


I am trying to upload files to an AWS S3 bucket from my Flutter app using the "aws_s3_upload" package, but I keep encountering a "Broken pipe" error. Here is the relevant part of my code:

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';
    }
  }

The error I receive is:

Failed to upload to AWS, with exception:
Broken pipe

Checked the internet connection, and it seems stable. Verified AWS credentials and S3 bucket policies to ensure they allow uploads. Tried increasing the timeout duration for requests. Made sure the file is not too large and is being read correctly. Logged more detailed error information.


Solution

  • `aws_s3_api: ^2.0.0` worker for me
    

    example:

    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;
        }