简体   繁体   English

如何从 dart:io 服务器上的 HTTPRequest 读取文件

[英]How to read file from HTTPRequest on a dart:io server

I am trying to create a server to run locally for my application to upload some files while debugging.我正在尝试创建一个服务器以在本地运行,以便我的应用程序在调试时上传一些文件。 It is very simple and the full source code is:它非常简单,完整的源代码是:

import 'dart:io';

void main(List<String> arguments) async {
  const port = 8080;
  final server = await HttpServer.bind(InternetAddress.anyIPv4, port);
  server.listen((request) async {
    if (request.uri.path != '/save_screenshot' || request.method != 'POST') {
      request.response.statusCode = 404;
      request.response.close();
      return;
    }

    // TODO: read the file
    request.response.statusCode = 200;
    request.response.close();
  });
  print('screenshot server listening on $port.');
}

At the code there is a TODO comment, where I would like to read the file from the HTTPRequest, I googled a bit and could not find a example to copy.在代码中有一个 TODO 注释,我想从 HTTPRequest 读取文件,我用谷歌搜索了一下,找不到要复制的示例。 Does anyone know how to read the file from the HTTPRequest?有谁知道如何从 HTTPRequest 读取文件?

Here is how it is being sent (on the client side):这是它的发送方式(在客户端):

final url = 'http://<local_ip_address>:8080/save_screenshot';
var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
  http.MultipartFile.fromBytes(
    'file',
    screenshot.bytes,
    filename: 'screenshot.png',
  ),
);
await request.send();

I found out how to read the file from the HTTPRequest.我发现了如何从 HTTPRequest 读取文件。 But for it to work it is necessary to install a package called mime .但是为了让它工作,必须安装一个名为mime的包。

Then replace the TODO comment in the question with:然后将问题中的 TODO 注释替换为:

final boundary = request.headers.contentType!.parameters['boundary']!;
final mimeTransformer = MimeMultipartTransformer(boundary);
final parts = request.cast<List<int>>().transform(mimeTransformer);
await for (final part in parts) {
  final file = File('uploaded_files/0.png');
  await part.pipe(file.openWrite());
}

I made a gist with the working server: https://gist.github.com/lslv1243/1036364b10c6578d969cb4ed2d7eba42我用工作服务器做了一个要点: https : //gist.github.com/lslv1243/1036364b10c6578d969cb4ed2d7eba42

NOTE: on the gist I changed the path from /save_screenshot to /screenshot注意:在要点上,我将路径从/save_screenshot/screenshot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM