breakPointUpload method

void breakPointUpload({
  1. required String filePath,
  2. ProgressCallback? onSendProgress,
  3. Success? success,
  4. Failure? failure,
  5. Completed? completed,
  6. dynamic cancelCallback()?,
  7. int? start,
})

断点上传

Implementation

void breakPointUpload({
  required String filePath,
  ProgressCallback? onSendProgress,
  Success? success,
  Failure? failure,
  Completed? completed,
  Function()? cancelCallback,
  int? start,
}) async {
  if (!(await _checkNetWork())) {
    return;
  }

  final url = _buildFinalUrl();

  var progress = start ?? 0;
  int fileSize = 0;
  File file = File(filePath);

  if (file.existsSync()) {
    fileSize = file.lengthSync();
  }

  var data = file.openRead(progress, fileSize - progress);

  try {
    _options?.method = _httpType.name;
    if (_headers.isNotEmpty) {
      _options?.headers?.addAll(_headers);
    }
    if (_enableGlobalHeader) {
      _options?.headers ??= {};
      _options?.headers?.addAll(_rxNet.getHeaders());
    }
    _options?.headers?.addAll({
      'Content-Range': 'bytes $progress-${fileSize - 1}/$fileSize'
    });

    // 准备请求体(如果有额外的body参数)
    // dynamic requestBody = _rawBody;
    // if (_rawBody == null && _bodyParams.isNotEmpty) {
    //   if (_bodyType == RequestBodyType.formData) {
    //     requestBody = FormData.fromMap(_bodyParams);
    //   } else if (_bodyType == RequestBodyType.json) {
    //     requestBody = _bodyParams;
    //   }
    // }

    final response = await _rxNet.client!.request<ResponseBody>(
      url,
      options: _options,
      cancelToken: _cancelToken,
      data: data,
      queryParameters: _queryParams,
    );

    onResponse?.call(response);
    Stream<Uint8List> stream = response.data!.stream;

    final subscription = stream.listen((data) {
      progress = progress + data.length;
      onSendProgress?.call(progress, fileSize);
    }, onDone: () async {
      success?.call(file, SourcesType.net);
    }, onError: (e) async {
      failure?.call(e);
    }, cancelOnError: true);

    _cancelToken?.whenCancel.then((_) async {
      await subscription.cancel();
      cancelCallback?.call();
    });
  } on DioException catch (error) {
    if (error.response != null) {
      if (progress <= fileSize) {
        onSendProgress?.call(progress, fileSize);
        success?.call(file, SourcesType.net);
      }
    }
    if (CancelToken.isCancel(error)) {
      cancelCallback?.call();
    } else {
      failure?.call(error);
    }
  }

  completed?.call();
}