download method

void download({
  1. required String savePath,
  2. ProgressCallback? onReceiveProgress,
  3. Success? success,
  4. Failure? failure,
  5. Completed? completed,
})

下载文件

Implementation

void download({
  required String savePath,
  adapter.ProgressCallback? onReceiveProgress,
  Success? success,
  Failure? failure,
  Completed? completed,
}) async {
  if (!(await _checkNetWork())) {
    return;
  }

  final url = _buildFinalUrl();

  try {
    // 准备请求体
    dynamic requestBody = _rawBody;
    if (_rawBody == null && _bodyParams.isNotEmpty) {
      if (_bodyType == RequestBodyType.formData) {
        requestBody = _bodyParams;
      } else if (_bodyType == RequestBodyType.json) {
        requestBody = _bodyParams;
      }
    }

    // 构建 AdapterRequest
    final adapterRequest = _buildAdapterRequest(
      url: url,
      queryParams: _queryParams,
      data: requestBody,
    );

    // 使用适配器下载文件
    final adapter = _rxNet.getAdapter();
    if (adapter == null) {
      throw NetworkException("NetworkAdapter is not initialized", null);
    }

    final response = await adapter.download(
      adapterRequest,
      savePath,
      onProgress: (received, total) {
        if (total != -1) {
          onReceiveProgress?.call(received, total);
        }
        if (received >= total) {
          success?.call(savePath, SourcesType.net);
        }
      },
    );

    onResponse?.call(response);
    if (!response.isSuccess) {
      failure?.call(response.data);
    }
  } on AdapterException catch (e) {
    failure?.call(e);
  } catch (e) {
    failure?.call(e);
  }
  completed?.call();
}