Using dart to download a file

2019-02-13 19:16发布

问题:

Can we use dart to download a file?

For example in python

回答1:

Shailen's response is correct and can even be a little shorter with Stream.pipe.

import 'dart:io';

main() {
  new HttpClient().getUrl(Uri.parse('http://example.com'))
    .then((HttpClientRequest request) => request.close())
    .then((HttpClientResponse response) => 
        response.pipe(new File('foo.txt').openWrite()));
}


回答2:

I'm using the HTTP package a lot. If you want to download a file that is not huge, you could use the HTTP package for a cleaner approach:

import 'package:http/http.dart' as http;

main() {
  http.get(url).then((response) {
    new File(path).writeAsBytes(response.bodyBytes);
  });
}

What Alexandre wrote will perform better for larger files. Consider writing a helper function for that if you find the need for downloading files often.



回答3:

The python example linked to in the question involves requesting the contents of example.com and writing the response to a file.

Here is how you can do something similar in Dart:

import 'dart:io';

main() {
  var url = Uri.parse('http://example.com');
  var httpClient = new HttpClient();
  httpClient.getUrl(url)
    .then((HttpClientRequest request) {
      return request.close();
    })
    .then((HttpClientResponse response) {
      response.transform(new StringDecoder()).toList().then((data) {
        var body = data.join('');
        print(body);
        var file = new File('foo.txt');
        file.writeAsString(body).then((_) {
          httpClient.close();
        });
      });
    });
}


回答4:

We can use http.readBytes(url).

await File(path).writeAsBytes(await http.readBytes('https://picsum.photos/200/300/?random'));



标签: dart