博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP后台代码 及 iOS客户端--AF实现上传视频
阅读量:5292 次
发布时间:2019-06-14

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

//视频转换为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];    }}}

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

后台PHP代码:

$json_result ['status'] = 0;$path = 'upload_video_file';$json_result ['status'] = 0;$json_result ['successmsg'] = '上传视频失败';if (isset ( $_FILES ['video'] )) {    $upfile = 'upload_video_file/' . $_FILES ['video'] ['name'];    if (! @file_exists ( $path )) {        @mkdir ( $path );    }    $result = @move_uploaded_file ( $_FILES ['video'] ['tmp_name'], $upfile );    if (! $result) {        $json_result ['status'] = 0;        $json_result ['successmsg'] = '上传视频失败';        $json_result ['datas'] = array ('savePath' =>  "http://".$_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT']."/".$upfile );        exit ( json_encode ( $json_result ) );    }}$json_result ['successmsg'] = '上传视频成功';$json_result ['status'] = 1;$json_result ['datas'] = array ('savePath' => "http://".$_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT']."/".$upfile );print_r(json_encode($json_result));

 

转载于:https://www.cnblogs.com/mafeng/p/5940262.html

你可能感兴趣的文章
右侧导航栏(动态添加数据到list)
查看>>
81、iOS本地推送与远程推送详解
查看>>
C#基础_注释和VS常用快捷键(一)
查看>>
虚拟DOM
查看>>
uva 11468 Substring
查看>>
自建数据源(RSO2)、及数据源增强
查看>>
BootStrap2学习日记2--将固定布局换成响应式布局
查看>>
关于View控件中的Context选择
查看>>
2018icpc徐州OnlineA Hard to prepare
查看>>
R语言-rnorm函数
查看>>
Spark的启动进程详解
查看>>
Java 字符终端上获取输入三种方式
查看>>
javascript 简单工厂
查看>>
java调用oracle存储过程,返回结果集
查看>>
使用命令创建数据库和表
查看>>
数据库的高级查询
查看>>
HttpClient(一)-- HelloWorld
查看>>
dump调试函数
查看>>
Android 利用Sharp样式设置文本框EditText圆角形状
查看>>
[YTU]_2443 ( C++习题 复数类--重载运算符3+)
查看>>