downloader.dart

// Copyright 2017 Matt Sullivan // Governed by the 2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause import 'dart:io'; import 'package:http/http.dart' as http; import 'package:args/args.dart'; void main(List<String> args) { var parsedArgs = parseArgs(args); // download(parsedArgs[0], parsedArgs[1]); progressiveDownload(parsedArgs[0], parsedArgs[1]); } /// Parse the command line args List<String> parseArgs(List<String> args) { var parser = new ArgParser() ..addOption('url', abbr: 'u', help: 'The url to download', valueHelp: 'url') ..addOption('filename', abbr: 'f', help: 'save filename', valueHelp: 'filename') ..addFlag('help', abbr: 'h', help: 'help info'); var parsedArgs = parser.parse(args); if (parsedArgs['help']) { print(parser.usage); exit(0); } String url; if (parsedArgs['url'] == null) { stderr.writeln('A url must be provided'); exit(1); } else { url = parsedArgs['url']; } var filename = parsedArgs['filename']; if (filename == null) { var uri = Uri.parse(url); filename = uri.pathSegments.isNotEmpty ? uri.pathSegments.last : 'output.html'; } return [url, filename]; } /// Downloads and saves the specified URI void download(String url, String filename) { http.get(Uri.parse(url)).then((res) { switch (res.statusCode) { case 200: print('Downloading content of length: ${res.contentLength}'); new File(filename).writeAsBytes(res.bodyBytes); break; default: stderr.writeln('Unexpected response code : ${res.statusCode}'); } }); } /// Progressively downloads and saves the specified URI void progressiveDownload(String url, String filename) { var req = new http.Request('GET', Uri.parse(url)); req.send().then((res) { if (res.statusCode == 200) { print('Downloading content of length: ${res.contentLength}'); res.stream.map((chunk) { print('Chunk size: ${chunk.length}'); return chunk; }).pipe(new File(filename).openWrite()); } else { stderr.writeln('Unexpected response code : ${res.statusCode}'); res.stream.drain(); } }); }
Simple HTTP downloader script in Dart

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.