multipart function

Future<Response> multipart(
  1. String url, {
  2. String method = 'POST',
  3. Map<String, String>? headers,
  4. Map<String, String>? body,
  5. String fileDataParam = 'file',
  6. List<FileData>? fileData,
})

Sends an HTTP multipart request with the given headers or body or file to the given URL.

Implementation

Future<Response> multipart(String url,
    {String method = 'POST',
    Map<String, String>? headers,
    Map<String, String>? body,
    String fileDataParam = 'file',
    List<FileData>? fileData}) async {
  var request = http_request.MultipartRequest(method, Uri.parse(url));

  if (headers != null) {
    request.headers.addAll(headers);
  }
  if (body != null) {
    request.fields.addAll(body);
  }

  if (fileData != null) {
    for (int i = 0; i < fileData.length; i++) {
      if (fileData[i].filePath.trim().isNotEmpty) {
        request.files.add(await http_request.MultipartFile.fromPath(
            '$fileDataParam[$i]', fileData[i].filePath,
            filename: fileData[i].fileName,
            contentType: MediaType.parse(fileData[i].fileMimeType)));
      }
    }
  }
  http_request.Response apiResponse =
      await http_request.Response.fromStream(await request.send());
  return Response(
      apiResponse.statusCode,
      apiResponse.body,
      apiResponse.bodyBytes,
      apiResponse.contentLength,
      apiResponse.headers,
      apiResponse.isRedirect,
      apiResponse.persistentConnection,
      apiResponse.reasonPhrase,
      apiResponse.request);
}