如何上传在DART文件?(How to upload a file in Dart?)

2019-07-03 16:22发布

我试图找到上传文件用飞镖脚本的任何实例。

我了解读它在文件输入字段被选中后,客户端的一部分,但我怎么能发送到服务器,并将其保存为一个文件?

Answer 1:

直到一个多编码解析器是可用的,你可以使用文件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);
  });
}

参考文献:

  • 通过File API使用JavaScript读取文件


文章来源: How to upload a file in Dart?