gpt4 book ai didi

file-upload - 如何在 Dart 中上传文件?

转载 作者:行者123 更新时间:2023-12-04 01:00:48 26 4
gpt4 key购买 nike

我正在尝试查找使用 Dart 脚本上传文件的任何示例。

我了解在文件输入字段中被选中后在客户端读取它的部分,但是如何将其发布到服务器并将其另存为文件?

最佳答案

在多部分编码解析器可用之前,您可以使用 File API在客户端读取和上传文件内容为 dataUrl .这个 API 在浏览器中有很好的支持(见 http://caniuse.com/filereader)。

在客户端:

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

在服务器端:

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

引用 :
  • Reading files in JavaScript using the File APIs
  • 关于file-upload - 如何在 Dart 中上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13298140/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com