问题
Using Dart and Golang for a small app and looking to upload a file to server.
Found something like this and placed it in my .dart file:
InputElement uploadInput = query('#file'); // my input type file
uploadInput.on.change.add((e) {
// read file content as dataURL
final files = uploadInput.files;
if (files.length == 1) {
final file = files[0];
final reader = new FileReader();
reader.on.load.add((e) {
sendDatas(reader.result);
});
reader.readAsDataURL(file);
}
});
but getting the following error:
Uncaught TypeError: Cannot read property 'get$on' of null
any idea how to handle this?
my goal: using input type file upload file to server (file size, < 1MB)
回答1:
This syntax has changed about a year ago.
try instead
uploadInput.onChange.listen((e) {
the same change is necessary here
reader.onLoad.listen((e) {
the xxx.on...
syntax is only for custom events or browser events where Dart doesn't yet have direct getters.
This also works for standard browser events. You can use it like
uploadInput.on['change'].listen((e) => doSomething());
回答2:
Finally changed the code and this is the final working function, uploading file with DART:
updatefileToPlay(Event e, dynamic data, FileUploadInputElement el) {
final files = el.files;
if (files.length == 1) {
final file = files[0];
final reader = new FileReader();
reader.onLoad.listen((e) {
FormData data = new FormData(); // from dart:html
data.append("file", file);
HttpRequest.request('/upload?id='+message.id, method: 'POST', sendData: data).then((HttpRequest r) {
if (r.readyState == HttpRequest.DONE &&
(r.status == 200 || r.status == 0)) {
window.alert("upload complete");
}
});
});
reader.readAsDataUrl(file);
}
}
来源:https://stackoverflow.com/questions/25568326/dart-upload-file-input-type-file