Using dart to download a file

Can we use dart to upload a file?

For example in python

+4
source share
3 answers

Shailen's answer is correct and may 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())); } 
+8
source

I am using an HTTP package. If you want to download a file that is not huge, you can 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 work better for large files. Consider writing a helper function for this if you often have to download files.

+8
source

The python example related to the question includes requesting the contents of example.com and writing the response to the file.

Here's how you can do something like this 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(); }); }); }); } 
+2
source

Source: https://habr.com/ru/post/1495093/


All Articles