OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 import "dart:async" show Future, Stream; |
| 6 import "dart:convert" show Encoding, LATIN1, UTF8; |
| 7 import "dart:html"; |
| 8 import "dart:typed_data" show Uint8List, ByteBuffer; |
| 9 |
| 10 /// Reads the bytes of a URI as a stream of bytes. |
| 11 Stream<List<int>> readAsStream(Uri uri) async* { |
| 12 // TODO(lrn): Should file be run through XmlHTTPRequest too? |
| 13 if (uri.scheme == "http" || uri.scheme == "https") { |
| 14 // TODO: Stream in chunks if DOM has a way to do so. |
| 15 List<int> response = await _httpGetBytes(uri); |
| 16 yield response; |
| 17 return; |
| 18 } |
| 19 if (uri.scheme == "data") { |
| 20 yield uri.data.contentAsBytes(); |
| 21 return; |
| 22 } |
| 23 throw new UnsupportedError("Unsupported scheme: $uri"); |
| 24 } |
| 25 |
| 26 /// Reads the bytes of a URI as a list of bytes. |
| 27 Future<List<int>> readAsBytes(Uri uri) async { |
| 28 if (uri.scheme == "http" || uri.scheme == "https") { |
| 29 return _httpGetBytes(uri); |
| 30 } |
| 31 if (uri.scheme == "data") { |
| 32 return uri.data.contentAsBytes(); |
| 33 } |
| 34 throw new UnsupportedError("Unsupported scheme: $uri"); |
| 35 } |
| 36 |
| 37 /// Reads the bytes of a URI as a string. |
| 38 Future<String> readAsString(Uri uri, Encoding encoding) async { |
| 39 if (uri.scheme == "http" || uri.scheme == "https") { |
| 40 // Fetch as string if the encoding is expected to be understood, |
| 41 // otherwise fetch as bytes and do decoding using the encoding. |
| 42 if (encoding != null) { |
| 43 return encoding.decode(await _httpGetBytes(uri)); |
| 44 } |
| 45 return HttpRequest.getString(uri.toString()); |
| 46 } |
| 47 if (uri.scheme == "data") { |
| 48 return uri.data.contentAsString(encoding: encoding); |
| 49 } |
| 50 throw new UnsupportedError("Unsupported scheme: $uri"); |
| 51 } |
| 52 |
| 53 Future<List<int>> _httpGetBytes(Uri uri) { |
| 54 return HttpRequest |
| 55 .request(uri.toString(), responseType: "arraybuffer") |
| 56 .then((request) { |
| 57 ByteBuffer data = request.response; |
| 58 return data.asUint8List(); |
| 59 }); |
| 60 } |
OLD | NEW |