Asynchronous API File Upload in Dart

This snippet demonstrates how to send API files using Dart's Http client, specifically for handling multipart requests. It includes functionality for attaching body data and multiple files, handling both JSON and file uploads efficiently while making asynchronous calls to ensure smooth execution.
 avatar
unknown
dart
a year ago
1.3 kB
6
Indexable
static sendAPIFiles({required String url,Map<String,String>? bodyData,List<XFile>? fileData,required String methodType}) async{
    var request = http.MultipartRequest('POST', Uri.parse(url));
    if(bodyData!=null){
      print("BODY DATA");
      print(bodyData.toString());
      request.fields.addAll(bodyData);
    }
    if (fileData != null) {
      fileData.forEach((element) async{
        var x=await http.MultipartFile.fromPath('images', element.path.toString());
        request.files.add(x);
      },);
      request.files.addAll(await Future.wait(
        fileData.map(
              (file) async => http.MultipartFile.fromPath('images', file.path.toString()),
        ),
      ));
    }
    print("request.files.length.toString()");
    print(request.files.length.toString());

    http.StreamedResponse response = await request.send();
    var responseBody=await response.stream.bytesToString();
    print("STATUS_CODE:::${response.statusCode}");
    print("URL=>${url}");
    print("BODY:::${responseBody}");
    Constant.StatusCode = response.statusCode.toString();
    if (response.statusCode == 200) {
      print(responseBody);
      return jsonDecode(responseBody);
    }
    else {
      print(response.reasonPhrase);
    }
  }
Editor is loading...
Leave a Comment