使用HTTP分块标头发送未知大小的数据的示例? [英] Examples that send unkown size data with http chunked header?

查看:149
本文介绍了使用HTTP分块标头发送未知大小的数据的示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了一些帖子和Wikipedia之后,我仍然不清楚chunked标头用法的实际示例.

I still don't have a clear picture of practical examples of the chunked header usage, after reading some posts and Wikipedia.

我从 Content-Length标头与分块编码看到的一个例子,是:

One example I see from Content-Length header versus chunked encoding, is:

另一方面,如果内容长度确实不可预测 事先(例如,当您打算将多个文件压缩在一起时, 将其作为一个发送),然后分块发送可能比 将其缓冲在服务器的内存中或写入本地磁盘文件系统 首先.

On the other hand, if the content length is really unpredictable beforehand (e.g. when your intent is to zip several files together and send it as one), then sending it in chunks may be faster than buffering it in server's memory or writing to local disk file system first.

所以这意味着我可以在压缩文件的同时发送zip文件吗?如何 ?

So it means that I can send zip files while I am zipping them ? How ?

我还注意到,如果下载GitHub存储库,我将在chunked中接收数据. GitHub是否也以这种方式发送文件(在压缩时发送)?

I've also noticed that if I download a GitHub repo, I am receiving data in chunked. Does GitHub also send files in this way (sending while zipping) ?

一个最小的例子将不胜感激. :)

A minimal example would be much appreciated. :)

推荐答案

下面是一个使用perl(带有IO :: Compress :: Zip模块)以@deceze指向的方式动态发送压缩文件的示例.

Here is an example using perl (with IO::Compress::Zip module) to send a zipped file on the fly as @deceze pointed to

use IO::Compress::Zip qw(:all);

my @files = ('example.gif', 'example1.png'); # here are some files

my $path = "/home/projects/"; # files location

# here is the header
print "Content-Type: application/zip\n"; # we are going to compress to zip and send it
print "Content-Disposition: attachment; filename=\"zip.zip\"\r\n\r\n"; # zip.zip for example is where we are going to zip data

my $zip = new IO::Compress::Zip;

foreach my $file (@files) {
  $zip->newStream(Name => $file, Method => ZIP_CM_STORE); # storing files in zip
  open(FILE, "<", "$path/$file");
  binmode FILE; # reading file in binary mode

  my ($buffer, $data, $n);

  while (($n = read FILE,$data, 1024) != 0) { # reading data from file to the end
     $zip->print($data); # print the data in binary
  }

  close(FILE);
}
$zip->close;

正如您在脚本中看到的那样,即使将zip文件名添加到标题中也没关系,因为我们正在压缩文件并立即以二进制模式打印它,因此无需压缩数据并存储它们,然后将其发送给客户端,您可以直接压缩文件并打印它们,而无需存储它们.

As you see in the script so even if you add the zip filename in the header, it doesn't matter, because we are zipping the files and printing it in binary mode right away, so it's not necessary to zip the data and store them then send it to the client, you can directly zip the files and print them without storing it.

这篇关于使用HTTP分块标头发送未知大小的数据的示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆