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);

    // 处理 RESTful 参数
    String path = request.path;
    request.pathParams.forEach((key, value) {
      path = path.replaceAll('{$key}', value.toString());
    });

    // 直接使用 path,Dio 会自动处理:
    // - 如果 path 是完整 URL (http:// 或 https://),Dio 直接使用
    // - 如果 path 是相对路径,Dio 会拼接 dio.options.baseUrl
    final response = await _dio.download(
      path,
      savePath,
      queryParameters: request.queryParams,
      data: requestBody,
      options: options,
      cancelToken: dioCancelToken,
      onReceiveProgress: onProgress,
    );

    return _convertFromResponse(response, request);
  } on DioException catch (e) {
    throw _convertException(e);
  }
}