#import "KUViewController.h"
#import "KU @interfaceKUViewController ()<NSURLsessionTaskDelegate> //下載進度的類,繼承UIview @property (weak, nonatomic) IBOutlet KUProgress *progressView; @end @implementation KUViewController - (void)viewDidLoad { [superviewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self putFile]; } /** * 用PUT方法上傳文件,不經過瀏覽器傳遞 */ -(void)putFile { //1,url(協議+主機名+路徑+保存到服務器的文件名) // post:url (協議+主機名+上傳的服務器的程序) NSString *urlStr = @"http://localhost/uploads/abc..mp4"; //1.1編碼格式 urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr]; //2,request 請求(默認是get) NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url]; //1>httpMethod request.HTTPMethod = @"PUT"; //2>網絡請求授權 /** BASE64目前在網絡上最流行的一種編碼方式,可以將二進制的數據轉換成字符串,對方接受到之后,可以再講字符串轉換成二進制文件 BASE64可以編碼,也可以解碼 授權格式: (1)授權字符串格式:用戶名:口令 (2)授權模式:Basic Base64編碼的授權字符串 (3)位HTTPHEADERField的Authorization賦值 */ NSString *authStr = @"admin:admin"; //將字符串轉換成 Base64 authStr = [self authBase64:authStr]; //轉換成第二部的 NSString *authBase64 = [NSString stringWithFormat:@"Basic %@",authStr]; //轉換成第三部 [request setValue:authBase64 forHTTPHeaderField:@"Authorization"]; //3,session //1>.創建會話機制 NSURLSessionConfiguration *config = [NSURLSessionConfigurationdefaultSessionConfiguration]; NSURLSession *session = [NSURLSessionsessionWithConfiguration:config delegate:selfdelegateQueue:[[NSOperationQueuealloc] init]]; //2> 上傳任務 //上傳的文件的路徑 NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"01.Post提交用戶隱私數據&md5加密.mp4" withExtension:nil]; [[session uploadTaskWithRequest:request fromFile:fileUrl] resume]; // 這是不用下載進度條的方法。 // NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:fileUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // // //把二進制數據轉換成字符串 // NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // NSLog(@"str = %@",str); // }]; // } #pragma mark -- 代理方法 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { CGFloat value = (CGFloat)totalBytesSent / totalBytesExpectedToSend; // [NSThread sleepForTimeInterval:0.2]; [[NSOperationQueuemainQueue] addOperationWithBlock:^{ self.progressView.progress = value; }]; NSLog(@"下載進度;value = %.03lf",value); } -(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error { NSLog(@"上傳失敗"); } //轉換成Base64編碼授權字符串 -(NSString *)authBase64:(NSString *)authStr { //將字符串轉換成二進制數局 NSData *data = [authStr dataUsingEncoding:NSUTF8StringEncoding]; return [data base64EncodedStringWithOptions:0]; }
新聞熱點
疑難解答