upload<T> method

Future<T?> upload<T>(
  1. String url, {
  2. required String filePath,
  3. String fieldName = 'file',
  4. Map<String, dynamic>? additionalFields,
  5. ProgressCallback? onProgress,
  6. String? fileName,
  7. String? contentType,
  8. CancelToken? cancelToken,
})

Upload a file using multipart/form-data.

url - The endpoint to upload the file to. filePath - The path to the file to upload. fieldName - The form field name for the file (default: 'file'). additionalFields - Optional additional form fields to include. onProgress - Optional callback for upload progress. fileName - Optional custom file name to use. contentType - Optional content type for the file.

Example:

final result = await api.upload<UploadResponse>(
  '/upload',
  filePath: '/path/to/image.jpg',
  fieldName: 'avatar',
  additionalFields: {'userId': '123'},
  onProgress: (sent, total) {
    print('Progress: ${(sent / total * 100).toStringAsFixed(0)}%');
  },
);

Implementation

Future<T?> upload<T>(
  String url, {
  required String filePath,
  String fieldName = 'file',
  Map<String, dynamic>? additionalFields,
  ProgressCallback? onProgress,
  String? fileName,
  String? contentType,
  CancelToken? cancelToken,
}) async {
  final formData = FormData.fromMap({
    fieldName: await MultipartFile.fromFile(
      filePath,
      filename: fileName,
      contentType: contentType != null
          ? DioMediaType.parse(contentType)
          : null,
    ),
    ...?additionalFields,
  });

  return await network<T>(
    request: (request) => request.postUri(
      Uri.parse(url),
      data: formData,
      cancelToken: cancelToken,
      onSendProgress: onProgress,
    ),
  );
}