如何在Dart中上传文件?

编程入门 行业动态 更新时间:2024-10-26 10:26:44
本文介绍了如何在Dart中上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图找到使用Dart脚本上传文件的任何示例。

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

我理解了在选择之后在客户端阅读的部分一个文件输入字段,但是如何POST到服务器并保存为一个文件?

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?

推荐答案

解析器,则可以在客户端上使用 File API 来阅读和上传文件内容作为 dataUrl 。此API在浏览器中提供了相当好的支持(请参阅 caniuse/filereader )。

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 caniuse/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", "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 = () { completerplete(""); }; sis.onError = (Exception e) { print('exeption occured : ${e.toString()}'); }; // process the request and send a response completer.future.then((_){ handleBody(bodyString); }); }

参考文献:

  • 使用File API读取JavaScript中的文件
  • Reading files in JavaScript using the File APIs

更多推荐

如何在Dart中上传文件?

本文发布于:2023-10-29 04:13:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538691.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上传文件   如何在   Dart

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!