uploadFile static method

Future<String> uploadFile(
  1. String path,
  2. File file, {
  3. Map<String, String>? headers,
  4. String fieldName = 'file',
  5. OnSuccess? onSuccess,
  6. OnError? onError,
})

Uploads a file via multipart POST to path.

fieldName defaults to 'file'. Returns the response body.

Implementation

static Future<String> uploadFile(
  String path,
  File file, {
  Map<String, String>? headers,
  String fieldName = 'file',
  OnSuccess? onSuccess,
  OnError? onError,
}) async {
  try {
    final request = http.MultipartRequest('POST', Uri.parse('$baseUrl$path'));
    request.headers.addAll({...defaultHeaders, ...?headers});
    request.files.add(
      await http.MultipartFile.fromPath(fieldName, file.path),
    );

    final streamed = await request.send();
    final resString = await streamed.stream.bytesToString();

    if (streamed.statusCode >= 200 && streamed.statusCode < 300) {
      onSuccess?.call(resString);
      return resString;
    } else {
      throw FinnUtilsClientException('Upload failed: $resString');
    }
  } catch (e) {
    onError?.call(FinnUtilsClientException(e.toString()));
    rethrow;
  }
}