21

Can we use dart to download a file?

For example in python

Community
  • 1
  • 1
Budi Sutrisno
  • 599
  • 1
  • 5
  • 12

5 Answers5

34

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.

Kai Sellgren
  • 27,954
  • 10
  • 75
  • 87
26

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

import 'dart:io';

main() async {
  final request = await HttpClient().getUrl(Uri.parse('http://example.com'));
  final response = await request.close();
  response.pipe(File('foo.txt').openWrite());
}
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • 1
    Doing this in a for loop would start all the downloads in parallel. How to serialize that? – Phani Rithvij Dec 30 '19 at 15:29
  • 2
    there is a memory leak in your example, the HttpClient is never closed. You must call `httpClient.close();` (The Shailen's response does) to avoid keeping the connection alive after the response. – Alex Rintt Feb 04 '23 at 16:20
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();
        });
      });
    });
}
Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
  • Ok so that's doable, but how about if the content is an image? Thank you. – Budi Sutrisno Aug 03 '13 at 14:38
  • Is the Dart API can not be shorter? `new HttpClient()` => `getUrl()` => `close()` => `transform()` => `new StringDecoder()` => `toList()` => `close()`. And this is without taking into account the 4 calls `then()`. – mezoni Aug 03 '13 at 18:19
  • 2
    Please note that the `StringDecoder` class has been replaced by `UTF8.decoder` in recent versions of Dart. – lucperkins Mar 17 '14 at 20:35
3

We can use http.readBytes(url).

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

Suyon Won
  • 346
  • 2
  • 8
1

Yes, first of all you have to request to file url using http dart library like:

Response response = await get(Uri.parse(link));

after that your Response object (response) will get that file in self and you can simply write the response bytes to a file and that file will be your downloaded file. as I open file like this:

File file = File('image.jpg')

then we have to send response bytes to this file like this:

file.writeAsBytes(response.bodyBytes);

now you have downloaded a image file successfully.. Congrates.

additional, for example let me show you a sample code to download a image file :

import 'dart:io';
import 'package:http/http.dart';
main(List<String> args) async {
var link =
  "https://pps.whatsapp.net/v/t61.24694- 
24/72779382_449683642563635_3243701117464346624_n.jpg?ccb=11- 
4&oh=23e3bc2ce3f4940a70cb464494bbda76&oe=619B3B8C";

Response response = await get(Uri.parse(link));
File file = File('image.jpg');
file.writeAsBytes(response.bodyBytes);
}

look, this is the code and a file named image.jpg is downloaded at bottom in terminal view is our downloaded image.

screen shot

this is our actual image which we downloaded.

downloaded image