Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file in Dart?

I'm trying to find any examples of uploading a file with a Dart script.

I understand the part about reading it on the client side after being selected in a file input field, but how can I POST it to the server and save it as a file?

like image 259
samer.ali Avatar asked Nov 08 '12 21:11

samer.ali


People also ask

Can we upload file using REST API?

REST API File Upload with Java In the above code block, we have created an endpoint of type HTTP Post that is waiting for file. This endpoint prints the name of the external file to the console of the application. That's all we'll do for File Upload on the code side.


1 Answers

Until a multipart encoding parser is available, you can use File API on client to read and upload file content as dataUrl. This API has quite good support in browsers ( see http://caniuse.com/filereader ).

On client side :

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

And on server side :

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

References :

  • Reading files in JavaScript using the File APIs
like image 165
Alexandre Ardhuin Avatar answered Oct 21 '22 06:10

Alexandre Ardhuin