我正在试验CGI和分块编码("Transfer- encoding : chunked“HTTP报头字段)。通过这种方式,可以在没有content-length报头的情况下发送文件。我用Ruby写了一个简约的CGI应用程序来试用它。我的代码如下(chunked.rb):
#!/usr/bin/ruby
puts "Date: Fri, 28 Nov 2015 09:59:59 GMT"
puts "Content-Type: application/octet-stream; charset=\"ASCII-8BIT\""
puts "Content-Disposition: attachment; filename=image.jpg"
puts "Transfer-Encoding: chunked"
puts
File.open("image.jpg","rb"){|f|
while data=f.read(32)
STDOUT.puts data.size.to_s(16)
STDOUT.puts data
end
STDOUT.puts "0"
STDOUT.puts
}我从这里获得了这个想法和分块格式示例:https://www.jmarshall.com/easy/http/
HTTP/1.1 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
1a; ignore-stuff-here
abcdefghijklmnopqrstuvwxyz
10
1234567890abcdef
0
some-footer: some-value
another-footer: another-value
[blank line here]因为我的CGI应用程序驻留在Apache cgi-bin目录中,所以我可以发出cURL:
curl http://example.com/cgi-bin/chunked.rb -O -JcURL应该从块中重新组合原始image.jpg文件,但不幸的是,保存的文件并不完整,它比原始文件小,并且我也从cURL收到了一条错误消息:
curl: (56) Malformed encoding found in chunked-encoding但是,当我将行data=f.read(32)更改为类似于data=f.read(1024*50)的内容时,文件将被正确保存。使用来自服务器的另一个更大的文件使CGI应用程序再次无用,我再次得到相同的错误信息。我该怎么做才能让我的CGI应用程序正常工作,并正确发送文件?
发布于 2015-11-29 13:46:10
因此,下面的工作示例:
puts "Date: Fri, 28 Nov 2015 09:59:59 GMT"
puts "Content-Type: application/octet-stream; charset=\"ASCII-8BIT\""
puts "Content-Disposition: attachment; filename=image.jpg"
puts "Transfer-Encoding: chunked"
puts
File.open("image.jpg","rb"){|f|
while data=f.read(32)
STDOUT.puts data.size.to_s(16)
STDOUT.print data
STDOUT.puts
end
STDOUT.puts "0"
STDOUT.puts
}https://stackoverflow.com/questions/33978822
复制相似问题