downloadUri method

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

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> downloadUri(
  Uri uri,
  dynamic savePath, {
  ProgressCallback? onReceiveProgress,
  CancelToken? cancelToken,
  bool deleteOnError = true,
  String lengthHeader = Headers.contentLengthHeader,
  Object? data,
  Options? options,
}) {
  return download(
    uri.toString(),
    savePath,
    onReceiveProgress: onReceiveProgress,
    lengthHeader: lengthHeader,
    deleteOnError: deleteOnError,
    cancelToken: cancelToken,
    data: data,
    options: options,
  );
}