2013-08-03 52 views

回答

8

Shailen's response是正确的,甚至可以用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

蟒蛇例如,在这个问题挂涉及请求的example.com内容,并写入文件的响应。

这里是你可以做类似的事情在飞镖:

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(); 
     }); 
     }); 
    }); 
} 
+0

好吧,这是可行的,但如果内容是图像怎么样?谢谢。 –

+0

Dart API不能更短吗? 'new new HttpClient()'=>'getUrl()'=>'close()'=>''close()''new StringDecoder()'=>'这是没有考虑到4次调用'然后()'。 – mezoni

+0

请注意,在最近版本的Dart中,'StringDecoder'类已被'UTF8.decoder'取代。 – lucperkins

8

我使用HTTP包很多。如果你想下载一个文件,是不是很大,你可以使用HTTP包一个更简洁的方法:

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

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

什么亚历山大写道:将较大文件有更好的表现。如果您经常需要下载文件,请考虑编写一个辅助函数。