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.

This automatically initializes a new Client and closes that client once the request is complete. If you're planning on making multiple requests to the same server, you should use a single Client for all of those requests.

Implementation

Future<http_request.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)));
      }
    }
  }

  return await http_request.Response.fromStream(await request.send());
}