利用put上传文件到服务器
#import "KUViewController.h"
#import "KUProgress.h"
@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];
}