Objective-c从URL检查文件大小而不下载 [英] Objective-c Check file size from URL without downloading
问题描述
我需要从URL检查文件的大小。使用AFNetworking下载文件时,我可以完美地获得文件大小。
AFHTTPRequestOperation * operation = [client HTTPRequestOperationWithRequest:request
success :^(AFHTTPRequestOperation * operation,id responseObject){
//成功回调
}失败:^(AFHTTPRequestOperation *操作,NSError *错误){
//失败回调
}];
并在另一个区块中获取文件大小
[operation setDownloadProgressBlock:^(NSUInteger bytesRead,long long totalBytesRead,long long totalBytesExpectedToRead){
}];
但我需要在启动下载请求之前检查文件大小,以便我可以提示用户。我还尝试了另一种方法
NSURL * url = [NSURL URLWithString:@http://lasp.colorado.edu/家用/可湿性粉剂内容/上传/ 2011/03 / suncombo1.jpg];
NSData * data = [NSData dataWithContentsOfURL:url];
NSLog(@original =%d,[数据长度]);
但它会阻止用户界面,因为它会下载所有数据以计算其大小。
下载前有没有办法检查文件大小?如果服务器支持它,你可以发出请求以获取标题(<$ p $ c> HEAD ,而不是 GET
),没有实际的数据有效负载,这应该包括 Content-Length
。
如果你不能这样做那么你需要开始下载并使用 expectedContentLength
NSURLResponse
。
基本上,创建一个实例 NSMutableURLRequest
并使用方法
参数设置为 setHTTPMethod:
@HEAD
(替换默认值 GET
)。然后在您当前请求提供完整数据集(相同的URL)时将其发送到服务器。
I need to check the size of file from a URL. I get the file size perfectly when downloading file with AFNetworking.
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Success Callback
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Failure Callback
}];
and get file size in another block
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
}];
But i need to check file size before initiating download request, so that i can prompt to user. I have also tried another method
NSURL *url = [NSURL URLWithString:@"http://lasp.colorado.edu/home/wp-content/uploads/2011/03/suncombo1.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(@"original = %d", [data length]);
But it blocks the UI, coz it download all data to calculate its size. Is there any way to check file size before downloading? Any help is appreciated.
If the server supports it you can make a request to just get the headers (HEAD
, as opposed to GET
) without the actual data payload and this should include the Content-Length
.
If you can't do that then you need to start the download and use expectedContentLength
of the NSURLResponse
.
Basically, create an instance of NSMutableURLRequest
and call setHTTPMethod:
with the method
parameter set to @"HEAD"
(to replace the default which is GET
). Then send that to the server as you currently request for the full set of data (same URL).
这篇关于Objective-c从URL检查文件大小而不下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!