Stream image file to HttpResponse efficiently

ぃ、小莉子 提交于 2019-12-06 15:24:00
Robert

I think this might help you - I got a speed up of about 4-5 times:

I will add my complete example here:

Future<ServerSocket> future = ServerSocket.bind("127.0.0.1", 1000);
future.then((ServerSocket sock) {
  HttpServer s = new HttpServer.listenOn(sock);

  s.listen((HttpRequest req) {
    req.response.statusCode = HttpStatus.OK;
    req.response.headers.contentType = ContentType.parse("image/png");
    var file = new File("someImage.png");

    // Average of about 5-7ms
    Future f = file.readAsBytes();
    req.response.addStream(f.asStream()).whenComplete(() {
      req.response.close();
    });
    // Average of ~25-30ms
    /*
    file.readAsBytes().then((List<int> bytes) {
      bytes.forEach((int b) => req.response.writeCharCode(b)); // slow!
      req.response.close();       
    });
    */ 
  });
});

Does this resolve your problem?

Regards Robert

Hector

Taking into account @Anders Johnsen's comment you could do this.

File f = new File( "image_file.png" )
  ..readAsBytes()
    .asStream()
    .pipe( req.response );

Personally I like this one because it makes use of Darts method cascading, but either works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!