'SocketException: OS Error: Broken pipe, errno = 32, port = 42644 error

I am trying to upload video file to the amazon S3 bucket and I am using amazon_cognito_identity_dart_2: ^1.0.5 plugin for uploading, but when I am trying to upload video file to AWS S3 bucket using Multipart, I am facing SocketException: OS Error: Broken pipe, errno = 32, address = address, port = 42644 error.

Please anyone let me know how I can resolve this issue. Thanks in advance.

Here is my workaround code.

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:amazon_cognito_identity_dart_2/sig_v4.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

class AWSClientService {

  Future<Map<String, String>> uploadData({
    @required String folderName,
    @required String fileName,
    @required Uint8List data,
    @required File fileDet,
    @required String filePath,
    @required String accessKeyId,
    @required String secretKeyId,
    @required String region,
    @required String bucketname,
    @required String s3Endpoint,
  }) async {
    final length = data.length;
    final uri = Uri.parse(s3Endpoint);
    var req = http.MultipartRequest("POST", uri);

    final multipartFile = http.MultipartFile(
      'videofiles',
      http.ByteStream.fromBytes(data),
      length,
      filename: fileName,
    );

    
    final policy = Policy.fromS3PresignedPost(
        folderName + fileName, bucketname, accessKeyId, 15, length,
        region: region);
    final key =
        SigV4.calculateSigningKey(secretKeyId, policy.datetime, region, 's3');
    final signature = SigV4.calculateSignature(
      key,
      policy.encode(),
    );

    print("Adding");
    req?.files?.add(multipartFile);
    print("Added");

    req.fields['key'] = policy.key;
    req.fields['acl'] = 'public-read';
    req.fields['X-Amz-Credential'] = policy.credential;
    req.fields['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256';
    req.fields['X-Amz-Date'] = policy.datetime;
    req.fields['Policy'] = policy.encode();
    req.fields['X-Amz-Signature'] = signature;

    
    try {
     
      var res = await req.send();
      

      var resp = res?.stream?.transform(utf8.decoder);
      
      if (res.statusCode == 200) {
        print("Status code: ${res.statusCode}");
        var bytes = <int>[];

        res.stream.listen((newBytes) {
          bytes.addAll(newBytes);
          print("Stream: $bytes");
        }).onDone(
          () async {
            await fileDet.writeAsBytes(bytes);
            print("On Done: $bytes");
          },
        );
      } else {
        
        var response = await http.Response.fromStream(res);
        
        if (response != null && response?.headers != null) {
          return response.headers;
        } else {
          return {};
        }
      }
    } catch (e) {
      
      print(e.toString());
      return e;
    }
  }
}

class Policy {
  String expiration;
  String region;
  String bucket;
  String key;
  String credential;
  String datetime;
  int maxFileSize;

  Policy(this.key, this.bucket, this.datetime, this.expiration, this.credential,
      this.maxFileSize,
      {this.region = 'ap-south-1'});

  factory Policy.fromS3PresignedPost(
    String key,
    String bucket,
    String accessKeyId,
    int expiryMinutes,
    int maxFileSize, {
    String region,
  }) {
    final datetime = SigV4.generateDatetime();
    final expiration = (DateTime.now())
        .add(Duration(minutes: expiryMinutes))
        .toUtc()
        .toString()
        .split(' ')
        .join('T');
    final cred =
        '$accessKeyId/${SigV4.buildCredentialScope(datetime, region, 's3')}';
    final p = Policy(key, bucket, datetime, expiration, cred, maxFileSize,
        region: region);
    return p;
  }

  String encode() {
    final bytes = utf8.encode(toString());
    return base64.encode(bytes);
  }

  @override
  String toString() {
    return '''
{ "expiration": "${this.expiration}",
  "conditions": [
    {"bucket": "${this.bucket}"},
    ["starts-with", "\$key", "${this.key}"],
    {"acl": "public-read"},
    ["content-length-range", 1, ${this.maxFileSize}],
    {"x-amz-credential": "${this.credential}"},
    {"x-amz-algorithm": "AWS4-HMAC-SHA256"},
    {"x-amz-date": "${this.datetime}" }
  ]
}
''';
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source