1、文件下載
php
獲取資源文件大小有兩張方式數組
一、xcode
- HTTP HEAD方法
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeout];
- request.HTTPMethod = @"HEAD";
- [NSURLConnection sendAsynchronousRequest:request queue:self.myQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
- NSLog(@"%@", response);
- NSLog(@"---------------");
- NSLog(@"%@", data);
- }];
- 運行測試代碼能夠發現,HEAD方法只是返回資源信息,而不會返回數據體
- 應用場景:
- 獲取資源Mimetype
- 獲取資源文件大小,用於端點續傳或多線程下載
2緩存
- 使用塊代碼獲取網絡資源大小的方法
- - (void)fileSizeWithURL:(NSURL *)url completion:(void (^)(long long contentLength))completion
- {
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeout];
- request.HTTPMethod = @"HEAD";
- NSURLResponse *response = nil;
- [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
-
- completion(response.expectedContentLength);
- }
肯定每次下載數據包的僞代碼實現服務器
- - (void)downloadFileWithURL:(NSURL *)url
- {
- [self fileSizeWithURL:url completion:^(long long contentLength) {
- NSLog(@"文件總大小:%lld", contentLength);
-
- while (contentLength > kDownloadBytes) {
- NSLog(@"每次下載長度:%lld", (long long)kDownloadBytes);
- contentLength -= kDownloadBytes;
- }
- NSLog(@"最後下載字節數:%lld", contentLength);
- }];
- }
HTTP Range的示例
經過設置Range能夠指定每次從網路下載數據包的大小
Range示例
bytes=0-499 從0到499的頭500個字節
bytes=500-999 從500到999的第二個500字節
bytes=500- 從500字節之後的全部字節
bytes=-500 最後500個字節
bytes=500-599,800-899 同時指定幾個範圍
Range小結
- 用於分隔
前面的數字表示起始字節數
後面的數組表示截止字節數,沒有表示到末尾
, 用於分組,能夠一次指定多個Range,不過不多用網絡
- 分段Range代碼實現
- long long fromBytes = 0;
- long long toBytes = 0;
- while (contentLength > kDownloadBytes) {
- toBytes = fromBytes + kDownloadBytes - 1;
- NSString *range = [NSString stringWithFormat:@"bytes=%lld-%lld", fromBytes, toBytes];
- NSLog(@"range %@", range);
- fromBytes += kDownloadBytes;
- contentLength -= kDownloadBytes;
- }
- fromBytes = fromBytes + contentLength - 1;
- NSString *range = [NSString stringWithFormat:@"bytes=%lld-%lld", fromBytes, toBytes];
- NSLog(@"range %@", range);
- 分段下載文件
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:kTimeout];
- NSString *range = [NSString stringWithFormat:@"bytes=%lld-%lld", from, end];
- [request setValue:range forHTTPHeaderField:@"Range"];
-
- NSURLResponse *response = nil;
- NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
-
- NSLog(@"%@-%@-%ld", range, response, (unsigned long)data.length);
- 提示:
- 若是GET包含Range請求頭,響應會以狀態碼206(PartialContent)返回而不是200(OK)
- 將數據寫入文件
- NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:self.cachePath];
- if (!fp) {
- [data writeToFile:self.cachePath atomically:YES];
- } else {
-
- [fp seekToEndOfFile];
-
- [fp writeData:data];
-
- [fp closeFile];
- }
- 檢查文件大小
- if ([[NSFileManager defaultManager] fileExistsAtPath:self.cachePath]) {
- NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:self.cachePath error:NULL];
- return [dict[NSFileSize] longLongValue];
- } else {
- return 0;
- }
-
- 提示:因爲數據是追加的,爲了不重複從網絡下載文件,在下載以前
- 判斷緩存路徑中文件是否已經存在
- 若是存在檢查文件大小
- 若是文件大小與網絡資源大小一致,則再也不下載
所有代碼以下多線程
-
- #import "MJViewController.h"
- #import "FileDownload.h"
-
- @interface MJViewController ()
- @property (nonatomic, strong) FileDownload *download;
- @property (weak, nonatomic) IBOutlet UIImageView *imageView;
- @end
-
- @implementation MJViewController
-
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
- self.download = [[FileDownload alloc] init];
- [self.download downloadFileWithURL:[NSURL URLWithString:@"http://localhost/itcast/images/head4.png"] completion:^(UIImage *image) {
-
- self.imageView.image = image;
- }];
- }
-
- @end
-
- #import "FileDownload.h"
- #import "NSString+Password.h"
-
- #define kTimeOut 2.0f
- #define kBytesPerTimes 20250
-
- @interface FileDownload()
- @property (nonatomic, strong) NSString *cacheFile;
- @property (nonatomic, strong) UIImage *cacheImage;
- @end
-
- @implementation FileDownload
- - (UIImage *)cacheImage
- {
- if (!_cacheImage) {
- _cacheImage = [UIImage imageWithContentsOfFile:self.cacheFile];
- }
- return _cacheImage;
- }
-
- - (void)setCacheFile:(NSString *)urlStr
- {
- NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
- urlStr = [urlStr MD5];
-
- _cacheFile = [cacheDir stringByAppendingPathComponent:urlStr];
- }
-
- - (void)downloadFileWithURL:(NSURL *)url completion:(void (^)(UIImage *image))completion
- {
-
- dispatch_queue_t q = dispatch_queue_create("cn.itcast.download", DISPATCH_QUEUE_SERIAL);
-
- dispatch_async(q, ^{
- NSLog(@"%@", [NSThread currentThread]);
-
-
- self.cacheFile = [url absoluteString];
-
-
- long long fileSize = [self fileSizeWithURL:url];
-
- long long cacheFileSize = [self localFileSize];
-
- if (cacheFileSize == fileSize) {
- dispatch_async(dispatch_get_main_queue(), ^{
- completion(self.cacheImage);
- });
- NSLog(@"文件已經存在");
- return;
- }
-
-
- long long fromB = 0;
- long long toB = 0;
-
- while (fileSize > kBytesPerTimes) {
-
-
- toB = fromB + kBytesPerTimes - 1;
-
-
- [self downloadDataWithURL:url fromB:fromB toB:toB];
-
- fileSize -= kBytesPerTimes;
- fromB += kBytesPerTimes;
- }
- [self downloadDataWithURL:url fromB:fromB toB:fromB + fileSize - 1];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- completion(self.cacheImage);
- });
- });
- }
-
- #pragma mark 下載指定字節範圍的數據包
- - (void)downloadDataWithURL:(NSURL *)url fromB:(long long)fromB toB:(long long)toB
- {
- NSLog(@"數據包:%@", [NSThread currentThread]);
-
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:kTimeOut];
-
-
- NSString *range = [NSString stringWithFormat:@"Bytes=%lld-%lld", fromB, toB];
- [request setValue:range forHTTPHeaderField:@"Range"];
- NSLog(@"%@", range);
-
- NSURLResponse *response = nil;
- NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
-
-
- [self appendData:data];
-
- NSLog(@"%@", response);
- }
-
- #pragma mark - 讀取本地緩存文件大小
- - (long long)localFileSize
- {
-
- NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:self.cacheFile error:NULL];
- NSLog(@"%lld", [dict[NSFileSize] longLongValue]);
-
- return [dict[NSFileSize] longLongValue];
- }
-
- #pragma mark - 追加數據到文件
- - (void)appendData:(NSData *)data
- {
-
- NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:self.cacheFile];
-
- if (!fp) {
- [data writeToFile:self.cacheFile atomically:YES];
- } else {
-
-
- [fp seekToEndOfFile];
-
- [fp writeData:data];
-
- [fp closeFile];
- }
- }
-
- #pragma mark - 獲取網絡文件大小
- - (long long)fileSizeWithURL:(NSURL *)url
- {
-
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeOut];
-
-
-
- request.HTTPMethod = @"HEAD";
-
-
- NSURLResponse *response = nil;
-
- [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
-
-
- NSLog(@"%lld", response.expectedContentLength);
-
- return response.expectedContentLength;
- }
-
- @end
2、文件上傳app
代碼以下dom
-
- #import "MJViewController.h"
- #import "UploadFile.h"
-
- @interface MJViewController ()
-
- @end
-
- @implementation MJViewController
-
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
- UploadFile *upload = [[UploadFile alloc] init];
-
- NSString *urlString = @"http://localhost/upload.php";
-
- NSString *path = [[NSBundle mainBundle] pathForResource:@"頭像1.png" ofType:nil];
- NSData *data = [NSData dataWithContentsOfFile:path];
-
- [upload uploadFileWithURL:[NSURL URLWithString:urlString] data:data];
- }
-
- @end
-
- #import "UploadFile.h"
-
- @implementation UploadFile
- static NSString *boundaryStr = @"--";
- static NSString *randomIDStr;
- static NSString *uploadID;
-
- - (instancetype)init
- {
- self = [super init];
- if (self) {
- randomIDStr = @"itcast";
- uploadID = @"uploadFile";
- }
- return self;
- }
-
- #pragma mark - 私有方法
- - (NSString *)topStringWithMimeType:(NSString *)mimeType uploadFile:(NSString *)uploadFile
- {
- NSMutableString *strM = [NSMutableString string];
-
- [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
- [strM appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\n", uploadID, uploadFile];
- [strM appendFormat:@"Content-Type: %@\n\n", mimeType];
-
- NSLog(@"%@", strM);
- return [strM copy];
- }
-
- - (NSString *)bottomString
- {
- NSMutableString *strM = [NSMutableString string];
-
- [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
- [strM appendString:@"Content-Disposition: form-data; name=\"submit\"\n\n"];
- [strM appendString:@"Submit\n"];
- [strM appendFormat:@"%@%@--\n", boundaryStr, randomIDStr];
-
- NSLog(@"%@", strM);
- return [strM copy];
- }
-
- #pragma mark - 上傳文件
- - (void)uploadFileWithURL:(NSURL *)url data:(NSData *)data
- {
-
- NSString *topStr = [self topStringWithMimeType:@"image/png" uploadFile:@"頭像1.png"];
- NSString *bottomStr = [self bottomString];
-
- NSMutableData *dataM = [NSMutableData data];
- [dataM appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]];
- [dataM appendData:data];
- [dataM appendData:[bottomStr dataUsingEncoding:NSUTF8StringEncoding]];
-
-
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f];
-
-
- request.HTTPBody = dataM;
-
-
- request.HTTPMethod = @"POST";
-
-
- NSString *strLength = [NSString stringWithFormat:@"%ld", (long)dataM.length];
- [request setValue:strLength forHTTPHeaderField:@"Content-Length"];
-
-
- NSString *strContentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", randomIDStr];
- [request setValue:strContentType forHTTPHeaderField:@"Content-Type"];
-
-
- [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
-
- NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- NSLog(@"%@", result);
- }];
- }
-
-
-
- @end