//創(chuàng)建會(huì)話
NSURLSession *session = [NSURLSessionsessionWithConfiguration:
//會(huì)話配置,導(dǎo)入?yún)f(xié)議,設(shè)置代理
[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:nil];
//上傳到哪個(gè)工程路徑
NSURL*url = [NSURL URLWithString:@"http://localhost:8080/UpLoad/NewServlet"];
//設(shè)置請(qǐng)求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//請(qǐng)求方式
[request setHTTPMethod:@"POST"];
//資源束,上傳內(nèi)容
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"11" ofType:@"jpg"];
//方式1
//轉(zhuǎn)化為二進(jìn)制流
NSData *data = [NSData dataWithContentsOfFile:filePath];
//設(shè)置上傳任務(wù)
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *_Nullabledata,NSURLResponse *_Nullableresponse,NSError *_Nullableerror) {
//返回文件上傳成功與否
NSLog(@"data ---> %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
//方式2
//設(shè)置文件路徑
NSURL*fileURL = [NSURL fileURLWithPath:filePath];
NSURLSessionUploadTask*task1 = [session uploadTaskWithRequest:request fromFile:fileURL completionHandler:^(NSData *_Nullabledata,NSURLResponse *_Nullableresponse,NSError *_Nullableerror) {
NSLog(@"data ---> %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//回到主線程刷新UI
[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:[UIImage imageWithContentsOfFile:filePath] waitUntilDone:NO];
}];
[task resume];
代理上傳!!!