//自己处理好自己的视频,压缩后生成data
- (void)uploadVideos:(NSArray *)videos andSource:(NSString *)source andUserId:(NSString *)userId andTitle:(NSString *)title andPart:(NSString *)part{
mytitle = [NSString stringWithString:title];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"……"]]cachePolicy:1 timeoutInterval:-1];
NSLog(@"request %@",request);
request.HTTPMethod = @"post";
// boundary可随意命名
NSString *boundary = @"yang";
// 拼接请求头
[request setValue:[NSString stringWithFormat:@"multipart/form-data;charset=utf-8;boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];
// 创建可变data 后面一样拼接
NSMutableData *myData = [NSMutableData data];
NSString *str = [NSString string];
NSString *name = @"userfile";
// 上传后文件的名字
NSString *filename = @"1.mp4";
//这个地方是关键,不能随意命名,很多地方缺少了了\n \r之类,若果格式命名不对 服务器可能会收到上传的文件
str = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\nContent-Type: %@\r\n\r\n",boundary,name,filename,@"video/quicktime"];
[myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
[myData appendData:[NSData dataWithData:videos[0]]];
str = [NSString stringWithFormat:@"\r\n--%@--",boundary];
[myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
request.HTTPBody = myData;
//执行上传
[[self.session uploadTaskWithRequest:request fromData:myData]resume];
//上传后监听上传进度
[self addProgressView];
}
// 懒加载 一个session
- (NSURLSession *)session
{
if(_session == nil)
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
}
return _session;
}
#pragma mark - 检测上传进度
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
_progress.hidden = NO;
showProgress = (float)totalBytesSent / totalBytesExpectedToSend;
NSLog(@"%f %@", showProgress, [NSThread currentThread]);
//UI主线程显示progress
[self performSelectorOnMainThread:@selector(showProgress) withObject:nil waitUntilDone:YES];
}