2

经过大量搜索后,我无法在通过 dart 上传时反序列化简单的文本文件。

我知道这可能会引发很多反对票,但是如何在 dart 中上传文件的简单演示会有所帮助吗?

无论是在控制台还是在 dart 的网络应用程序中。我只想上传一个包含一些基本单词的文本文件。

4

1 回答 1

6

以下简单示例适用于我:

在编辑器中使用以下文件结构:

fileuploadtest/
  fileupload.dart
  index.html

index.html(注意:这里没有 Dart!)

<!DOCTYPE html>

<html>
  <head>
    <title>index</title>
  </head>

  <body>   
    <form enctype="multipart/form-data" action="foo" method="POST">
      <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
        Choose a file to upload: <input name="uploadedfile" type="file" /><br />
      <input type="submit" value="Upload File" />
    </form>   
  </body>
</html>

文件上传.dart

这将创建一个静态文件处理程序(为简单起见)始终index.html响应任何GET请求,以及一个文件上传处理程序响应任何 POST 请求并打印出上传文件的内容(实际上,整个 POST 数据 - 你'必须提取相关位)。

import 'dart:io';

void main() {
  var httpServer = new HttpServer();

  // attach handlers:

  var static = new StaticFileHandler();
  httpServer.addRequestHandler(static.matcher, static.handler);

  var fileUploadHandler = new FileUploadHandler();
  httpServer.addRequestHandler(fileUploadHandler.matcher, 
      fileUploadHandler.handler);

  // start listening
  httpServer.listen("127.0.0.1", 8081);
}

class FileUploadHandler {
  bool matcher(req) => req.method == "POST"; // return true if method is POST

  void handler(req,res) {
    req.inputStream.onData = () {
      var data = req.inputStream.read();
      var content = new String.fromCharCodes(data);
      print(content); // print the file content.
    };
  }
}

class StaticFileHandler {
  //  return true for all GET requests.
  bool matcher(req) {
    print("Path: ${req.path}");
    return req.method=="GET"; 
  }

  void handler(req,res) {
    var file = new File("index.html"); // only serve index.html in the same folder
    file.openInputStream().pipe(res.outputStream);
  }
}

启动fileUpload.dart并使用浏览器导航到http://localhost:8081/index.html

对于名为 的文件foo.txt,包含以下内容:

foo
bar

这是我得到的整个日志输出(从 Dart 编辑器的控制台发布)

------WebKitFormBoundaryw7XBqLKuA7nP1sKc

Content-Disposition: form-data; name="MAX_FILE_SIZE"

100000

------WebKitFormBoundaryw7XBqLKuA7nP1sKc

Content-Disposition: form-data; name="uploadedfile"; filename="foo.txt"

Content-Type: text/plain

foo
bar

------WebKitFormBoundaryw7XBqLKuA7nP1sKc--
于 2013-01-29T16:49:24.043 回答