天天看點

下載下傳時擷取檔案大小

下載下傳時擷取檔案大小

下載下傳時擷取檔案大小

擷取檔案大小,有時候會出現檔案大小為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屬性就出來了。

繼續閱讀