PHP后台代码 及 iOS客户端--AF实现上传视频
//视频转换为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<AFMultipartFormData> 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" mimeType
AFURLSessionManager *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));
PHP后台代码 及 iOS客户端--AF实现上传视频的更多相关文章
- 在C#客户端用HTTP上传文件到Java服务器
在C#客户端用HTTP上传文件到Java服务器 来源:http://www.cnblogs.com/AndyDai/p/5135294.html 最近在做C / S 开发,需要在C#客户端上传文件到 ...
- ios 上传视频或图片
关于iOS如何实现视频和图片的上传, 我们先理清下思路 思路: #1. 如何获取图片? #2. 如何获取视频? #3. 如何把图片存到缓存路径中? #4. 如何把视频存到缓存路径中? #5. 如何上传 ...
- Java模拟客户端向服务器上传文件
先来了解一下客户端与服务器Tcp通信的基本步骤: 服务器端先启动,然后启动客户端向服务器端发送数据. 服务器端收到客户端发送的数据,服务器端会响应应客户端,向客户端发送响应结果. 客户端读取服务器发送 ...
- java客户端文件的上传和下载
java客户端文件的上传和下载 //上传 public JTable upload(String id){ JTable table=new JTable(); System.out.println( ...
- iOS:给Git仓库上传代码时,超过100M会被拒绝(例如github和oschina)
处理GitHub不允许上传大于100M文件问题?本人也遇到这个坑... 来自转载,原文链接:http://www.cnblogs.com/qmmq/p/4604862.html 1.报错: 自己的项目 ...
- 【转】 iOS开发之打包上传到App Store——(一)各种证书的理解
OK,有日子没写iOS开发的相关文章啦,主要是最近的精力都没在这上面,不过既然产品已经快要出来了,就有必要了解一下各种证书啥的(众所周知iOS的一堆证书可是很让人头大呀),最近确实被这个搞得头大,然后 ...
- web api 如何通过接收文件流的方式,接收客户端及前端上传的文件
服务端接收文件流代码: public async Task<HttpResponseMessage> ReceiveFileByStream() { var stream = HttpCo ...
- 5行代码实现微信小程序图片上传与腾讯免费5G存储空间的使用
本文介绍了如何在微信小程序开发中使用腾讯官方提供的云开发功能快速实现图片的上传与存储,以及介绍云开发的 5G 存储空间的基本使用方法,这将大大提高微信小程序的开发效率,同时也是微信小程序系列教程的视频 ...
- 基于前台vue,后台是spring boot的压缩图片上传
本人是刚毕业的新手,最近公司的一个项目,前后端分离,前端Vue,后端使用spring boot.其中有一个需求是需要做前端上传的图片需要压缩才能上传.为此在网上查找资料,并做了简单的实现. 那么一步来 ...
随机推荐
- linux原始套接字(1)-arp请求与接收
一.概述 以太网的arp数据包结构: arp结构op操作参数:1为请求,2为应答. 常用的数据结构如 ...
- [uwsgi] no request plugin is loaded, you will not be able to manage requests.
Problem: *** Operational MODE: preforking+threaded no app loaded. going in full dynamic mode uWSGI i ...
- [转]Oracle 分组聚合二种写法,listagg和wmsys.wm_concat
本文转自:http://www.cnblogs.com/ycdx2001/p/3502495.html with temp as( select 'China' nation ,'Guangzhou' ...
- Java开发之JSP行为
一.Java Bean行文 1.重点说明 Java Bean行为是一组与Java Bean相关的行为,包括useBean行为.setProperty行为.getProperty行为等.Java Bea ...
- 给深度学习入门者的Python快速教程 - numpy和Matplotlib篇
始终无法有效把word排版好的粘贴过来,排版更佳版本请见知乎文章: https://zhuanlan.zhihu.com/p/24309547 实在搞不定博客园的排版,排版更佳的版本在: 给深度学习入 ...
- CF722D. Generating Sets[贪心 STL]
D. Generating Sets time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- BC#86 1003NanoApe Loves Sequence Ⅱ[two-pointer]
NanoApe Loves Sequence Ⅱ Accepts: 374 Submissions: 946 Time Limit: 4000/2000 MS (Java/Others) Me ...
- POJ3463Sightseeing[次短路计数]
Sightseeing Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 8707 Accepted: 3056 Descr ...
- javascript删除元素节点
1.删除元素父节点 function removeElement(_element){ var _parentElement = _element.parentNode; if(_parentElem ...
- Android Fragment 你应该知道的一切
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/42628537,本文出自:[张鸿洋的博客] 很久以前写过两篇Fragment的介绍 ...