Dart Language: receive a file from a POST and prin

2019-06-10 18:39发布

问题:

I would like to know how can a server side application receive a file (via POST) and then print its contents on the server side.

The most "up to date" related question here was this one: Dart how to upload image

But it is not working anymore (Uncaught Error: type 'String' is not a subtype of type 'HttpBodyFileUpload' of 'fileUploaded').

EDIT:

This is how I send the file (this method is working fine):

import 'dart:html';
import 'dart:async';

HttpRequest request = new HttpRequest();
final _HOST = "127.0.0.1", _PORT = 8123;

Future sendFile(File file) {
    var completer = new Completer(); // No need for a Completer. It will be removed.
    Uri uri = new Uri(host: _HOST, port: _PORT);
    request.open("POST", uri.toString());
    var filename = file.name;
    final FormData formData = new FormData();
    formData.append('file', filename);
    request.onLoadEnd.listen((_) {
        completer.complete(request.response);
    });
    request.send(formData);
    return completer.future;
}

The server side (I'm stuck here):

void _handlePost(HttpRequest req) {
    HttpBodyHandler.processRequest(req).then((body) {
        HttpBodyFileUpload fileUploaded = body.body['file'];
        print(fileUploaded.content);
    });
}

回答1:

You are appending the filename instead of the Blob (File) to your FormData object. In Dart it looks like there is a special function for appending blobs called appendBlob(name, blob, [filename]).



标签: dart server