download method

  1. @override
Future<AdapterResponse> download(
  1. AdapterRequest request,
  2. String savePath, {
  3. ProgressCallback? onProgress,
})
override

Downloads a file from the server.

This method downloads a file and saves it to the specified path on the device. Progress can be tracked using the optional onProgress callback.

Parameters:

  • request: The request configuration for the download
  • savePath: The local file path where the downloaded file will be saved
  • onProgress: Optional callback to track download progress

Returns a Future that completes with an AdapterResponse when the download is complete.

Throws AdapterException if the download fails.

Example:

final request = AdapterRequest(
  baseUrl: 'https://example.com',
  path: '/files/document.pdf',
  method: HttpMethod.get,
);

await adapter.download(
  request,
  '/path/to/save/document.pdf',
  onProgress: (count, total) {
    print('Downloaded: ${(count / total * 100).toStringAsFixed(1)}%');
  },
);

Implementation

@override
Future<AdapterResponse> download(
  AdapterRequest request,
  String savePath, {
  ProgressCallback? onProgress,
}) async {
  try {
    final options = _convertToOptions(request);
    final requestBody = _buildRequestBody(request);
    final dioCancelToken = _convertCancelToken(request.cancelToken);

    try {
      // 下载与普通请求保持一致,统一使用规范化后的完整 URL。
      final response = await _dio.download(
        request.buildFullUrl(),
        savePath,
        queryParameters: request.queryParams,
        data: requestBody,
        options: options,
        cancelToken: dioCancelToken,
        onReceiveProgress: onProgress,
      );

      return _convertFromResponse(response, request);
    } finally {
      _cancelTokenMap.remove(request.cancelToken);
    }
  } on DioException catch (e) {
    throw _convertException(e);
  }
}