博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
第五十三篇、OC利用AFN上传视频到服务器
阅读量:5952 次
发布时间:2019-06-19

本文共 5722 字,大约阅读时间需要 19 分钟。

整体思路已经清楚,拿到视频资源,先转为mp4,写进沙盒,然后上传,上传成功后删除沙盒中的文件。

本地拍摄的视频,上传到服务器:

//视频转换为MP4     //转码操作...     _hud.mode = MBProgressHUDModeIndeterminate;     _hud.labelText = @"转码中...";    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:_filePathURL  options:nil];     NSDateFormatter* formater = [[NSDateFormatter alloc] init];     [formater setDateFormat:@"yyyyMMddHHmmss"];    _fileName = [NSString stringWithFormat:@"output-%@.mp4",[formater stringFromDate:[NSDate date]]];    _outfilePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@", _fileName];    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];    if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality])    {        MyLog(@"outPath = %@",_outfilePath);        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];        exportSession.outputURL = [NSURL fileURLWithPath:_outfilePath];        exportSession.outputFileType = AVFileTypeMPEG4;        [exportSession exportAsynchronouslyWithCompletionHandler:^{            if ([exportSession status] == AVAssetExportSessionStatusCompleted) {                MyLog(@"AVAssetExportSessionStatusCompleted---转换成功");                _filePath = _outfilePath;                _filePathURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@",_outfilePath]];                 MyLog(@"转换完成_filePath = %@\n_filePathURL = %@",_filePath,_filePathURL);                //获取大小和长度                [self SetViewText];                [self uploadNetWorkWithParam:@{
@"contenttype":@"application/octet-stream",@"discription":description}]; }else{ MyLog(@"转换失败,值为:%li,可能的原因:%@",(long)[exportSession status],[[exportSession error] localizedDescription]); [_hud hide:YES]; [MyHelper showAlertWith:nil txt:@"转换失败,请重试"]; } }]; }#pragma mark - 开始上传-(void)uploadNetWorkWithParam:(NSDictionary*)dict{ MyLog(@"开始上传_filePath = %@\n_filePathURL = %@",_filePath,_filePathURL);AFHTTPRequestSerializer *ser=[[AFHTTPRequestSerializer alloc]init];NSMutableURLRequest *request =[ser multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",kBaseUrl,kVideoUploadUrl] parameters:@{
@"path":@"show",@"key":_key,@"discription":dict[@"discription"],@"isimage":@(_isImage)} constructingBodyWithBlock:^(id
formData) { [formData appendPartWithFileURL:_filePathURL name:@"file" fileName:_fileName mimeType:dict[@"contenttype"] error:nil]; if (!_isImage) { [formData appendPartWithFileURL:_path2Url name:@"tmp" fileName:@"tmp.PNG" mimeType:@"image/png" error:nil]; } } error:nil];//@"image/png" @"application/octet-stream" mimeTypeAFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];NSProgress *progress = nil;NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { if (error) { MyLog(@"request = %@", request ); MyLog(@"response = %@", response ); MyLog(@"Error: %@", error ); [_hud hide:YES]; CXAlertView *alert=[[CXAlertView alloc]initWithTitle:NSLocalizedString(@"Warning", nil) message:NSLocalizedString(@"Upload Failed",nil) cancelButtonTitle:NSLocalizedString(@"Iknow", nil)]; alert.showBlurBackground = NO; [alert show]; } else { MyLog(@"%@ %@", response, responseObject); NSDictionary *backDict=(NSDictionary *)responseObject; if ([backDict[@"success"] boolValue] != NO) { _hud.labelText = NSLocalizedString(@"Updating", nil); [self UpdateResxDateWithDict:backDict discription:dict[@"discription"]]; [_hud hide:YES]; }else{ [_hud hide:YES]; [MyHelper showAlertWith:nil txt:backDict[@"msg"]]; } } [progress removeObserver:self forKeyPath:@"fractionCompleted" context:NULL];}];[progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];[progress setUserInfoObject:@"someThing" forKey:@"Y.X."];[uploadTask resume];}

 

删除沙盒中的视频:

#pragma mark - 清除documents中的视频文件-(void)ClearMovieFromDoucments{NSFileManager *fileManager = [NSFileManager defaultManager];NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];NSEnumerator *e = [contents objectEnumerator];NSString *filename;while ((filename = [e nextObject])) {    MyLog(@"%@",filename);    if ([filename isEqualToString:@"tmp.PNG"]) {        MyLog(@"删除%@",filename);        [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];        continue;    }    if ([[[filename pathExtension] lowercaseString] isEqualToString:@"mp4"]||        [[[filename pathExtension] lowercaseString] isEqualToString:@"mov"]||        [[[filename pathExtension] lowercaseString] isEqualToString:@"png"]) {        MyLog(@"删除%@",filename);        [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];    }}}

 

转载于:https://www.cnblogs.com/HJQ2016/p/5962813.html

你可能感兴趣的文章
Java 集合框架查阅技巧
查看>>
apache配置虚拟主机
查看>>
CollectionView水平和竖直瀑布流的实现
查看>>
前端知识复习一(css)
查看>>
spark集群启动步骤及web ui查看
查看>>
Maven学习笔记二:常用命令
查看>>
利用WCF改进文件流传输的三种方式
查看>>
程序员的素养
查看>>
Spring学习总结(2)——Spring的常用注解
查看>>
关于IT行业人员吃的都是青春饭?[透彻讲解]
查看>>
钱到用时方恨少(随记)
查看>>
mybatis主键返回的实现
查看>>
org.openqa.selenium.StaleElementReferenceException
查看>>
Android Intent传递对象为什么要序列化?
查看>>
数论之 莫比乌斯函数
查看>>
linux下查找某个文件位置的方法
查看>>
python之MySQL学习——数据操作
查看>>
Harmonic Number (II)
查看>>
长连接、短连接、长轮询和WebSocket
查看>>
day30 模拟ssh远程执行命令
查看>>