网站添加视频后发布到服务器上,iOS开发实战 - 上传视频到服务器

本文介绍如何使用AFN将本地拍摄的视频转码为mp4格式,并上传至服务器的方法。主要内容包括视频转码、上传及清理临时文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里介绍用AFN上传本地拍摄的视频到服务端

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

压缩导出视频

- (void)transcoding {

// 转码操作...

_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]) {

NSLog(@"outPath = %@", _outfilePath);

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];

exportSession.outputURL = [NSURL fileURLWithPath:_outfilePath];

exportSession.outputFileType = AVFileTypeMPEG4;

[exportSession exportAsynchronouslyWithCompletionHandler:^{

if ([exportSession status] == AVAssetExportSessionStatusCompleted) {

NSLog(@"AVAssetExportSessionStatusCompleted--转换成功");

_filePath = _outfilePath;

_filePathURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@", _outfilePath]];

NSLog(@"转换完成_filePath = %@\n_filePathURL = %@", _filePath, _filePathURL);

// 获取大小和长度

[self SetViewText];

[self uploadNetWorkWithParam:@{@"contenttype" : @"application/octet-stream", @"discription" : description}];

} else {

NSLog(@"转换失败,值为:%li, 可能的原因:%@", (long)[exportSession status], [[exportSession error] localizedDescription]);

[_hud hide:YES];

[MyHelper showAlertWith:nil txt:@"转换失败,请重试"];

}

}];

}

}

开始上传

- (void)uploadNetWorkWithParam:(NSDictionary*)dict {

NSLog(@"开始上传_filePath = %@\n_filePathURL = %@", _filePath, _filePathURL);

AFHTTPRequestSerializer *serializer=[[AFHTTPRequestSerializer alloc] init];

NSString *urlString = [NSString stringWithFormat:@"%@%@", kBaseUrl, kVideoUploadUrl];

NSDictionary *parameters = @{@"path" : @"show", @"key" : _key, @"discription" : dict[@"discription"], @"isimage" : @(_isImage)};

NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST"

URLString:urlString

parameters:parameters

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" 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) {

NSLog(@"request = %@", request);

NSLog(@"response = %@", response);

NSLog(@"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 {

NSLog(@"%@ %@", 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];

}

清除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])) {

NSLog(@"%@", filename);

if ([filename isEqualToString:@"tmp.PNG"]) {

NSLog(@"删除%@", 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"]) {

NSLog(@"删除%@",filename);

[fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值