Web Server随文件一起发送数据

时间:2012-12-12 11:58:56

标签: dart

我想向客户端提供一个html页面以及一些json,而无需在客户端进行往返的往返。这可能吗?这样做的最佳方法是什么?我考虑过把它发送到标题中,但似乎有些人不赞同。任何例子都非常感谢。 Psuedo代码:

main(){
  ...
  app.addRequestHandler((req) => req.path == '/user', handler);
}

void handler(req, res) {
  var file = new File(myHtmlFile);
  res.headers.set(...); //add json here?
  res.outputstream...   //or here?
  ...
  stream.pipe(res.outputStream);
}

1 个答案:

答案 0 :(得分:2)

在您的html文件中,您可以在发送作为回复之前添加标记

例如,在你的html文件中:

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
</head>
<body>
  <input type='hidden' id='datas' value="___JSON_DATAS___"/>
  ...
</body>
</html>

___JSON_DATAS___将在您的服务器中替换为:

void handler(req, res) {
  var file = new File(myHtmlFile);
  readStreamAsString(file.openInputStream()).then((fileContent) {
    final content = fileContent
        .replaceAll("___JSON_DATAS___", htmlEscape(jsonAsString));
    res.outputStream.writeAsString(content);
    res.outputStream.close();
  });
}

String htmlEscape(String text) {
  return text.replaceAll("&", "&amp;")
      .replaceAll("<", "&lt;")
      .replaceAll(">", "&gt;")
      .replaceAll('"', "&quot;")
      .replaceAll("'", "&apos;");
}

Future<String> readStreamAsString(InputStream stream) {
  final completer = new Completer();
  final sb = new StringBuffer();
  final sis = new StringInputStream(stream);
  sis
    ..onData = () { sb.add(sis.read()); }
    ..onClosed = () { completer.complete(sb.toString()); }
    ..onError = (e) { completer.completeException(e); };
  return completer.future;
}

然后,在客户端:

import 'dart:html';
import 'dart:json';

main(){
  final input = query('#datas') as InputElement;
  final datas = JSON.parse(input.value);
  //...
}