美文网首页
NSURLSession上传

NSURLSession上传

作者: nothing_c | 来源:发表于2016-10-28 01:05 被阅读41次

//创建会话

NSURLSession *session = [NSURLSessionsessionWithConfiguration:


//会话配置,导入协议,设置代理

[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:nil];

//上传到哪个工程路径

NSURL*url = [NSURL URLWithString:@"http://localhost:8080/UpLoad/NewServlet"];

//设置请求

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//请求方式

[request setHTTPMethod:@"POST"];

//资源束,上传内容

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"11" ofType:@"jpg"];

//方式1

//转化为二进制流

NSData *data = [NSData dataWithContentsOfFile:filePath];

//设置上传任务

NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *_Nullabledata,NSURLResponse *_Nullableresponse,NSError *_Nullableerror) {

//返回文件上传成功与否

NSLog(@"data ---> %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

}];

//方式2

//设置文件路径

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];

代理上传!!!

相关文章

网友评论

      本文标题:NSURLSession上传

      本文链接:https://www.haomeiwen.com/subject/axwsuttx.html