download method

  1. @override
Future<Response> download(
  1. String urlPath,
  2. dynamic savePath, {
  3. ProgressCallback? onReceiveProgress,
  4. Map<String, dynamic>? queryParameters,
  5. CancelToken? cancelToken,
  6. bool deleteOnError = true,
  7. String lengthHeader = Headers.contentLengthHeader,
  8. Object? data,
  9. Options? options,
})
override

Download the file and save it in local. The default http method is "GET", you can custom it by Options.method.

urlPath is the file url.

The file will be saved to the path specified by savePath. The following two types are accepted:

  1. String: A path, eg "xs.jpg"
  2. FutureOr<String> Function(Headers headers), for example:
    await dio.download(
      url,
      (Headers headers) {
        // Extra info: redirect counts
        print(headers.value('redirects'));
        // Extra info: real uri
        print(headers.value('uri'));
        // ...
        return (await getTemporaryDirectory()).path + 'file_name';
      },
    );
    

onReceiveProgress is the callback to listen downloading progress. Please refer to ProgressCallback.

deleteOnError whether delete the file when error occurs. The default value is true.

lengthHeader : The real size of original file (not compressed). When file is compressed:

  1. If this value is 'content-length', the total argument of onReceiveProgress will be -1.
  2. If this value is not 'content-length', maybe a custom header indicates the original file size, the total argument of onReceiveProgress will be this header value.

You can also disable the compression by specifying the 'accept-encoding' header value as '*' to assure the value of total argument of onReceiveProgress is not -1. For example:

await dio.download(
  url,
  (await getTemporaryDirectory()).path + 'flutter.svg',
  options: Options(
    headers: {HttpHeaders.acceptEncodingHeader: '*'}, // Disable gzip
  ),
  onReceiveProgress: (received, total) {
    if (total <= 0) return;
    print('percentage: ${(received / total * 100).toStringAsFixed(0)}%');
  },
);

Implementation

@override
Future<Response> download(
  String urlPath,
  dynamic savePath, {
  ProgressCallback? onReceiveProgress,
  Map<String, dynamic>? queryParameters,
  CancelToken? cancelToken,
  bool deleteOnError = true,
  String lengthHeader = Headers.contentLengthHeader,
  Object? data,
  Options? options,
}) {
  throw UnsupportedError(
    'The download method is not available in the Web environment.',
  );
}