IBRIT
IBRIT

Reputation: 385

How to upload a file from input type file in dart?

After searching a lot I am unable to deserialise a simple text file while uploading through dart.

I know this may trigger lot of down votes but a simple demo of how to upload files in dart would be helpful ?

both in console as well in web app in dart.I just want to upload a text file with some basic words in it nothing else.

Upvotes: 2

Views: 2285

Answers (1)

Chris Buckett
Chris Buckett

Reputation: 14398

The following simple example works for me:

With the following file structure in the editor:

fileuploadtest/
  fileupload.dart
  index.html

index.html (note: no Dart here!)

<!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>

fileupload.dart

This creates a static file handler that (for simplicity) always serves index.html in response to any GET request , and a File Upload Handler that responds to any POST request and prints out the content of an uploaded file (well, actually, the entire POST data - you'll have to extract the relevant bit).

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);
  }
}

Start fileUpload.dart and use an browser to navigate to http://localhost:8081/index.html

For a file called foo.txt, containing the following content:

foo
bar

This is the entire log output I get (posted from the the Dart Editor's console)

------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--

Upvotes: 6

Related Questions