https://github.com/YouXianMing

下载时获取文件大小

下载时获取文件大小

获取文件大小,有时候会出现文件大小为0的情况,一般来说,这是由于我们无法获取文件头中的“Content-Length”造成,通常有两种原因:

 

1. 服务器压根就没有设置这个属性(现在的服务器基本上都有)

2. 由于将“Accept-Encoding“设置为gzip,就是压缩传输,从而将Content-Length属性隐藏了,导致我们无法获取

 

The expected content length is only set when the server provides it, such as by a Content-Length response header. A -1 size means the expected content size is unknown.

If you set Accept-Encoding: gzip on your request, the URL loading system will fib and tell you the expected size is -1, no matter what Content-Length the server sends. This is because it decompresses the data before passing it to you, but it can't know the final uncompressed size till all the data has been downloaded, which is well after you receive this callback.

 

针对第二种情况,首先可以检查响应头中的Accept-Encoding“的属性是否为"gzip",如果是的话,就在下载请求中手动设置Accept-Encoding“:

[req setValue:@""forHTTPHeaderField:@"Accept-Encoding"];

这时候再去检查响应头,Content-Length属性就出来了。

 

 

posted @ 2014-06-14 16:39  YouXianMing  阅读(2256)  评论(0编辑  收藏  举报