IOS 上傳下載
阿新 • • 發佈:2017-05-30
cor and etc patch sof 網絡文件 bmp time sar
下載地址:https://github.com/samsoffes/ssziparchive
註意:需要引入libz.dylib框架
// Unzipping
NSString *zipPath = @"path_to_your_zip_file";
NSString *destinationPath = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];
// Zipping
NSString *zippedPath = @"path_where_you_want_the_file_created";
NSArray *inputPaths = [NSArray arrayWithObjects:
[[NSBundle mainBundle] pathForResource:@"photo1" ofType:@"jpg"],
[[NSBundle mainBundle] pathForResource:@"photo2" ofType:@"jpg"]
nil];
[SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];
Content-Type multipart/form-data; boundary=本次上傳標示字符串(不能中文)
--本次上傳標示字符串 \n
Content-Disposition: form-data; name="服務端字段"; filename="上傳文件名" \n
Content-Type: 上傳文件MIMEType \n\n
要上傳的二進制數據
--本次上傳標示字符串 \n
Content-Disposition: form-data; name="submit" \n\n
Submit \n
--本次上傳標示字符串-- \n
類型 |
文件拓展名 |
MIMEType |
圖片 |
png |
image/png |
bmp\dib |
image/bmp |
|
jpe\jpeg\jpg |
image/jpeg |
|
gif |
image/gif |
|
多媒體 |
mp3 |
audio/mpeg |
mp4\mpg4\m4vmp4v |
video/mp4 |
|
文本 |
js |
application/javascript |
|
application/pdf |
|
text\txt |
text/plain |
|
json |
application/json |
|
xml |
text/xml |
post上傳
// // UploadFile.m // 02.Post上傳 #import "UploadFile.h" @implementation UploadFile // 拼接字符串 static NSString *boundaryStr = @"--"; // 分隔字符串 static NSString *randomIDStr; // 本次上傳標示字符串 static NSString *uploadID; // 上傳(php)腳本中,接收文件字段 - (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 { // 1> 數據體 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]]; // 1. Request NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f]; // dataM出了作用域就會被釋放,因此不用copy request.HTTPBody = dataM; // 2> 設置Request的頭屬性 request.HTTPMethod = @"POST"; // 3> 設置Content-Length NSString *strLength = [NSString stringWithFormat:@"%ld", (long)dataM.length]; [request setValue:strLength forHTTPHeaderField:@"Content-Length"]; // 4> 設置Content-Type NSString *strContentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", randomIDStr]; [request setValue:strContentType forHTTPHeaderField:@"Content-Type"]; // 3> 連接服務器發送請求 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", result); }]; } @endView Code
// // MJViewController.m // 02.Post上傳 #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]; } @endView Code
文件下載
// // FileDownload.m // 01.文件下載 // #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 /** 為了保證開發的簡單,所有方法都不使用多線程,所有的註意力都保持在文件下載上 在開發中如果碰到比較繞的計算問題時,建議: 1> 測試數據不要太大 2> 測試數據的數值變化,能夠用筆算計算出準確的數值 3> 編寫代碼對照測試 */ //- (NSString *)cacheFile //{ // if (!_cacheFile) { // NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; // _cacheFile = [cacheDir stringByAppendingPathComponent:@"123.png"]; // } // return _cacheFile; //} - (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 { // GCD中的串行隊列異步方法 dispatch_queue_t q = dispatch_queue_create("cn.itcast.download", DISPATCH_QUEUE_SERIAL); dispatch_async(q, ^{ NSLog(@"%@", [NSThread currentThread]); // 把對URL進行MD5加密之後的結果當成文件名 self.cacheFile = [url absoluteString]; // 1. 從網絡下載文件,需要知道這個文件的大小 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; } // 2. 確定每個數據包的大小 long long fromB = 0; long long toB = 0; // 計算起始和結束的字節數 while (fileSize > kBytesPerTimes) { // 20480 + 20480 // toB = fromB + kBytesPerTimes - 1; // 3. 分段下載文件 [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 下載指定字節範圍的數據包 /** NSURLRequestUseProtocolCachePolicy = 0, // 默認的緩存策略,內存緩存 NSURLRequestReloadIgnoringLocalCacheData = 1, // 忽略本地的內存緩存 NSURLRequestReloadIgnoringCacheData */ - (void)downloadDataWithURL:(NSURL *)url fromB:(long long)fromB toB:(long long)toB { NSLog(@"數據包:%@", [NSThread currentThread]); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:kTimeOut]; // 指定請求中所要GET的字節範圍 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]; // 寫入文件,覆蓋文件不會追加 // [data writeToFile:@"/Users/aplle/Desktop/1.png" atomically:YES]; [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 { // 如果文件已經存在追加文件 // 1> 移動到文件末尾 [fp seekToEndOfFile]; // 2> 追加數據 [fp writeData:data]; // 3> 寫入文件 [fp closeFile]; } } #pragma mark - 獲取網絡文件大小 - (long long)fileSizeWithURL:(NSURL *)url { // 默認是GET NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeOut]; // HEAD 頭,只是返回文件資源的信息,不返回具體是數據 // 如果要獲取資源的MIMEType,也必須用HEAD,否則,數據會被重復下載兩次 request.HTTPMethod = @"HEAD"; // 使用同步方法獲取文件大小 NSURLResponse *response = nil; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL]; // expectedContentLength文件在網絡上的大小 NSLog(@"%lld", response.expectedContentLength); return response.expectedContentLength; } @endView Code
// // MJViewController.m // 01.文件下載 // // Created by apple on 14-4-29. // Copyright (c) 2014年 itcast. All rights reserved. // #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; }]; } @endView Code
Post Json解析數據
// // MJViewController.m // 03.Post JSON // #import "MJViewController.h" #import "Person.h" @interface MJViewController () @end @implementation MJViewController /** 序列化: 將字典或數組變成順序(序列的)二進制數據流,以便於網絡傳輸 反序列化: 將從網絡接收到的二進制數據流,轉換成數據和字典的過程 */ - (void)viewDidLoad { [super viewDidLoad]; [self postObj]; } - (void)postObj { // 1. URL NSURL *url = [NSURL URLWithString:@"http://localhost/postjson.php"]; // 2. Request NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f]; request.HTTPMethod = @"POST"; Person *p = [[Person alloc] init]; p.name = @"zhang"; p.age = 19; // KVC給對象賦值 // p setValuesForKeysWithDictionary:<#(NSDictionary *)#> // 使用KVC把對象變成字典 // 需要指定對象的屬性的鍵值數組 // 數組中指定的鍵值,必須是對象的屬性 // 錯誤示例1 // id obj = [p dictionaryWithValuesForKeys:@[@"name", @"age1"]]; // 鍵值數組中,不一定要包含全部的屬性 id obj = [p dictionaryWithValuesForKeys:@[@"name"]]; // id obj = [p dictionaryWithValuesForKeys:@[@"name", @"age"]]; // 提示dataWithJSONObject只能對NSDictionary和NSArray進行序列化 request.HTTPBody = [NSJSONSerialization dataWithJSONObject:obj options:0 error:NULL]; // 3. Connection [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", result); }]; } - (void)postJSON { // 1. URL NSURL *url = [NSURL URLWithString:@"http://localhost/postjson.php"]; // 2. Request NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f]; request.HTTPMethod = @"POST"; // 在iOS中JSON就是Dict/Array // 使用NSDictionary & NSArray可以各種靈活組合 NSDictionary *dict = @{ @"name": @"zhangsan", @"age" : @18, @"book" : @[ @"iOS 1", @"iOS 2" ], @"zoom" : @1 }; NSDictionary *dict1 = @{ @"name": @"lisi", @"age" : @24, @"book" : @[ @"iOS 7", @"iOS 6" ], @"zoom" : @2 }; NSArray *array = @[dict, dict1]; // 把字典轉換成二進制數據流, 序列化 request.HTTPBody = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL]; // 將data轉換成NSDictionary 反序列化 // [NSJSONSerialization JSONObjectWithData:<#(NSData *)#> options:<#(NSJSONReadingOptions)#> error:<#(NSError *__autoreleasing *)#>] // 3. Connection [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", result); }]; } @endView Code
URLSessin文件上傳
// // MJViewController.m // 04.URLSessin Upload // #import "MJViewController.h" @interface MJViewController () @end @implementation MJViewController - (void)viewDidLoad { [super viewDidLoad]; [self uploadFile]; } #pragma mark - 用Session上傳頭像 - (void)uploadFile { // 1. NSURL NSString *urlString = @"http://localhost/uploads/測試一下.png"; urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlString]; // NSURL *url = [NSURL URLWithString:@"http://localhost/uploads/測試一下.png"]; // 2. Request NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0]; request.HTTPMethod = @"PUT"; // 設置用戶授權 // 1> "admin:123456" NSString *authStr = @"admin:123456"; // 2> result = 對字符串進行BASE64編碼(網絡傳輸中常用的一種編碼格式,NSData) NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding]; NSString *result = [authData base64EncodedStringWithOptions:0]; // 3> "Basic result" => 提交給服務器的驗證字符串,用來驗證身份 NSString *authString = [NSString stringWithFormat:@"Basic %@", result]; // 設置HTTP請求頭的數值,設置用戶授權 [request setValue:authString forHTTPHeaderField:@"Authorization"]; // 3. Session,有一個單例,是全局共享的 NSURLSession *session = [NSURLSession sharedSession]; // 4. 文件上傳 NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"頭像1.png" withExtension:nil]; // 所有任務默認都是掛起的 NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:bundleURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // 上傳完成操作 NSLog(@"%@", response); }]; [task resume]; } @endView Code
IOS 上傳下載