我试图找到任何使用Dart脚本上传文件的例子.

我理解在文件输入字段中 Select 后在客户端阅读的部分,但如何将其发布到服务器并保存为文件?

推荐答案

在提供分块编码解析器之前,您可以在客户端使用File API作为dataUrl读取和上传文件内容.此API在浏览器中有相当好的支持(参见http://caniuse.com/filereader).

在客户端:

import 'dart:html';

main() {
  InputElement uploadInput = query('#upload');
  uploadInput.onChange.listen((e) {
    // read file content as dataURL
    final files = uploadInput.files;
    if (files.length == 1) {
      final file = files[0];
      final reader = new FileReader();
      reader.onLoad.listen((e) {
        sendDatas(reader.result);
      });
      reader.readAsDataUrl(file);
    }
  });
}

/// send data to server
sendDatas(dynamic data) {
  final req = new HttpRequest();
  req.onReadyStateChange.listen((Event e) {
    if (req.readyState == HttpRequest.DONE &&
        (req.status == 200 || req.status == 0)) {
      window.alert("upload complete");
    }
  });
  req.open("POST", "http://127.0.0.1:8080/upload");
  req.send(data);
}

在服务器端:

import 'dart:io';

main() {
  final server = new HttpServer();
  server.listen('127.0.0.1', 8080);
  server.addRequestHandler((request) => request.path == '/upload' 
      && request.method.toLowerCase() == 'post'
      , (HttpRequest request, HttpResponse response) {
    _readBody(request, (body) {

      // handle your dataURL
      // example with image : data:image/jpeg;base64,/9j/4S2YRXhpZgAATU0AK... 

      // return result
      response.statusCode = HttpStatus.CREATED;
      response.contentLength = 0;
      response.outputStream.close();
    });
  });
}

/// Read body of [request] and call [handleBody] when complete.
_readBody(HttpRequest request, void handleBody(String body)) {
  String bodyString = ""; // request body byte data
  final completer = new Completer();
  final sis = new StringInputStream(request.inputStream, Encoding.UTF_8);
  sis.onData = (){
    bodyString = bodyString.concat(sis.read());
  };
  sis.onClosed = () {
    completer.complete("");
  };
  sis.onError = (Exception e) {
    print('exeption occured : ${e.toString()}');
  };
  // process the request and send a response
  completer.future.then((_){
    handleBody(bodyString);
  });
}

参考资料:

Dart相关问答推荐

如何判断一个数字是否是dart中另一个数字的倍数?

flutter.io (dart) - 将填充设置为设备宽度的百分比?

Flutter 是否提供即时应用程序?

Flutter pod 安装问题 - # 的未定义方法 `each_child'

如何在 Flutter 中将 textEditiing 控制器与 Provider 一起使用

SliverList / SliverChildBuilderDelegate 提供初始索引或允许负索引

如何go 除字符串中的变音符号?

异常:在Flatter项目上没有Linux桌面项目配置错误

Flutter ToggleButton 类 - Flutter 1.9.1

在Flutter 中使用 import 'dart:html' - 我需要额外的依赖项吗?

在 TextInputType 更改后控制器重置的 Flutter TextField

如何从 ExpansionTile 的标题中删除默认填充

Dart 工厂构造函数 - 它与const构造函数有何不同

具有列表的 Null 感知运算符

Dart vs Polymer vs Bootstrap

导出两个具有相同类名的库

dart中 library关键字的确切含义

GWT 与 Dart - 主要区别是什么? Dart 是 GWT 的潜在替代品吗?

Dart 中的错误与异常

如何在 Dart 中创建私有变量?