关于iOS如何实现视频和图片的上传, 我们先理清下思路,然后小编根据思路一步一步给大家详解实现过程。

思路:

#1. 如何获取图片?

#2. 如何获取视频?

#3. 如何把图片存到缓存路径中?

#4. 如何把视频存到缓存路径中?

#5. 如何上传?

接下来, 我们按照上面的思路一步一步实现

首先我们新建一个类, 用来储存每一个要上传的文件uploadModel.h

#import

@interface uploadModel : NSObject

@property (nonatomic, strong) NSString *path;

@property (nonatomic, strong) NSString *type;

@property (nonatomic, strong) NSString *name;

@property (nonatomic, assign) BOOL isUploaded;

@end

#1. 如何获取图片?

从相册选择 或者 拍照,

这部分可以用UIImagePickerController来实现

代码如下:

- (void)actionPhoto {

UIAlertController *alertController = \

[UIAlertController alertControllerWithTitle:@""

message:@"上传照片"

preferredStyle:UIAlertControllerStyleActionSheet];

UIAlertAction *photoAction = \

[UIAlertAction actionWithTitle:@"从相册选择"

style:UIAlertActionStyleDefault

handler:^(UIAlertAction * _Nonnull action) {

NSLog(@"从相册选择");

self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];

self.imagePicker.allowsEditing = YES;

[self presentViewController:self.imagePicker

animated:YES

completion:nil];

}];

UIAlertAction *cameraAction = \

[UIAlertAction actionWithTitle:@"拍照"

style:UIAlertActionStyleDefault

handler:^(UIAlertAction * _Nonnull action) {

NSLog(@"拍照");

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;

self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;

self.imagePicker.allowsEditing = YES;

[self presentViewController:self.imagePicker

animated:YES

completion:nil];

}

}];

UIAlertAction *cancelAction = \

[UIAlertAction actionWithTitle:@"取消"

style:UIAlertActionStyleCancel

handler:^(UIAlertAction * _Nonnull action) {

NSLog(@"取消");

}];

[alertController addAction:photoAction];

[alertController addAction:cameraAction];

[alertController addAction:cancelAction];

[self presentViewController:alertController animated:YES completion:nil];

}

#2. 如果获取视频?

从相册选择 或者 拍摄

这部分也可以用UIImagePickerController来实现

代码:

- (void)actionVideo {

UIAlertController *alertController = \

[UIAlertController alertControllerWithTitle:@""

message:@"上传视频"

preferredStyle:UIAlertControllerStyleActionSheet];

UIAlertAction *photoAction = \

[UIAlertAction actionWithTitle:@"从视频库选择"

style:UIAlertActionStyleDefault

handler:^(UIAlertAction * _Nonnull action) {

NSLog(@"从视频库选择");

self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

self.imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];

self.imagePicker.allowsEditing = NO;

[self presentViewController:self.imagePicker animated:YES completion:nil];

}];

UIAlertAction *cameraAction = \

[UIAlertAction actionWithTitle:@"录像"

style:UIAlertActionStyleDefault

handler:^(UIAlertAction * _Nonnull action) {

NSLog(@"录像");

self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;

self.imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];

self.imagePicker.videoQuality = UIImagePickerControllerQualityType640x480;

self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;

self.imagePicker.allowsEditing = YES;

[self presentViewController:self.imagePicker animated:YES completion:nil];

}];

UIAlertAction *cancelAction = \

[UIAlertAction actionWithTitle:@"取消"

style:UIAlertActionStyleCancel

handler:^(UIAlertAction * _Nonnull action) {

NSLog(@"取消");

}];

[alertController addAction:photoAction];

[alertController addAction:cameraAction];

[alertController addAction:cancelAction];

[self presentViewController:alertController animated:YES completion:nil];

}

#3, 关于缓存, 如何把照片存入缓存目录?

这部分我们先考虑缓存目录, 一般存在Document 或者 Temp里面

我们给图片和视频各创建一个缓存目录:

#define PHOTOCACHEPATH [NSTemporaryDirectory() stringByAppendingPathComponent:@"photoCache"]

#define VIDEOCACHEPATH [NSTemporaryDirectory() stringByAppendingPathComponent:@"videoCache"]

把UIImage存入缓存的方法:

//将Image保存到缓存路径中

- (void)saveImage:(UIImage *)image toCachePath:(NSString *)path {

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:PHOTOCACHEPATH]) {

NSLog(@"路径不存在, 创建路径");

[fileManager createDirectoryAtPath:PHOTOCACHEPATH

withIntermediateDirectories:YES

attributes:nil

error:nil];

} else {

NSLog(@"路径存在");

}

//[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];

[UIImageJPEGRepresentation(image, 1) writeToFile:path atomically:YES];

}

4. 如何把视频存入缓存?

把视频存入缓存的方法:

//将视频保存到缓存路径中

- (void)saveVideoFromPath:(NSString *)videoPath toCachePath:(NSString *)path {

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:VIDEOCACHEPATH]) {

NSLog(@"路径不存在, 创建路径");

[fileManager createDirectoryAtPath:VIDEOCACHEPATH

withIntermediateDirectories:YES

attributes:nil

error:nil];

} else {

NSLog(@"路径存在");

}

NSError *error;

[fileManager copyItemAtPath:videoPath toPath:path error:&error];

if (error) {

NSLog(@"文件保存到缓存失败");

}

}

从缓存获取图片的方法:

//从缓存路径获取照片

- (UIImage *)getImageFromPath:(NSString *)path {

NSFileManager *fileManager = [NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:path]) {

return [UIImage imageWithContentsOfFile:path];

}

return nil;

}

上传图片和视频的时候我们一般会利用当前时间给文件命名, 方法如下

//以当前时间合成图片名称

- (NSString *)getImageNameBaseCurrentTime {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];

return [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:@".JPG"];

}

//以当前时间合成视频名称

- (NSString *)getVideoNameBaseCurrentTime {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];

return [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:@".MOV"];

}

有时候需要获取视频的第一帧作为显示, 方法如下:

//获取视频的第一帧截图, 返回UIImage

//需要导入AVFoundation.h

- (UIImage*) getVideoPreViewImageWithPath:(NSURL *)videoPath

{

AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoPath options:nil];

AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];

gen.appliesPreferredTrackTransform = YES;

CMTime time = CMTimeMakeWithSeconds(0.0, 600);

NSError *error = nil;

CMTime actualTime;

CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];

UIImage *img = [[UIImage alloc] initWithCGImage:image];

return img;

}

5. 如何上传?

下面就是上传方法:

我把服务器地址xx掉了, 大家可以改为自己的

//上传图片和视频

- (void)uploadImageAndMovieBaseModel:(uploadModel *)model {

//获取文件的后缀名

NSString *extension = [model.name componentsSeparatedByString:@"."].lastObject;

//设置mimeType

NSString *mimeType;

if ([model.type isEqualToString:@"image"]) {

mimeType = [NSString stringWithFormat:@"image/%@", extension];

} else {

mimeType = [NSString stringWithFormat:@"video/%@", extension];

}

//创建AFHTTPSessionManager

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

//设置响应文件类型为JSON类型

manager.responseSerializer = [AFJSONResponseSerializer serializer];

//初始化requestSerializer

manager.requestSerializer = [AFHTTPRequestSerializer serializer];

manager.responseSerializer.acceptableContentTypes = nil;

//设置timeout

[manager.requestSerializer setTimeoutInterval:20.0];

//设置请求头类型

[manager.requestSerializer setValue:@"form/data" forHTTPHeaderField:@"Content-Type"];

//设置请求头, 授权码

[manager.requestSerializer setValue:@"YgAhCMxEehT4N/DmhKkA/M0npN3KO0X8PMrNl17+hogw944GDGpzvypteMemdWb9nlzz7mk1jBa/0fpOtxeZUA==" forHTTPHeaderField:@"Authentication"];

//上传服务器接口

NSString *url = [NSString stringWithFormat:@"http://xxxxx.xxxx.xxx.xx.x"];

//开始上传

[manager POST:url parameters:nil constructingBodyWithBlock:^(id _Nonnull formData) {

NSError *error;

BOOL success = [formData appendPartWithFileURL:[NSURL fileURLWithPath:model.path] name:model.name fileName:model.name mimeType:mimeType error:&error];

if (!success) {

NSLog(@"appendPartWithFileURL error: %@", error);

}

} progress:^(NSProgress * _Nonnull uploadProgress) {

NSLog(@"上传进度: %f", uploadProgress.fractionCompleted);

} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {

NSLog(@"成功返回: %@", responseObject);

model.isUploaded = YES;

[self.uploadedArray addObject:model];

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

NSLog(@"上传失败: %@", error);

model.isUploaded = NO;

}];

}

这里有事先创建两个可变数组uploadArray, uploadedArray, 一个存放准要上传的内容, 一个存放上传完的内容

在准备上传后做什么操作, 可以检查两个数组的数量是否相等

最后是UIImagePickerController的协议方法

#pragma mark - UIImagePickerDelegate methods

- (void)imagePickerController:(UIImagePickerController *)picker

didFinishPickingMediaWithInfo:(NSDictionary *)info {

[picker dismissViewControllerAnimated:YES completion:nil];

//获取用户选择或拍摄的是照片还是视频

NSString *mediaType = info[UIImagePickerControllerMediaType];

if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {

//获取编辑后的照片

NSLog(@"获取编辑后的好片");

UIImage *tempImage = info[UIImagePickerControllerEditedImage];

//将照片存入相册

if (tempImage) {

if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {

//将照片存入相册

NSLog(@"将照片存入相册");

UIImageWriteToSavedPhotosAlbum(tempImage, self, nil, nil);

}

//获取图片名称

NSLog(@"获取图片名称");

NSString *imageName = [self getImageNameBaseCurrentTime];

NSLog(@"图片名称: %@", imageName);

//将图片存入缓存

NSLog(@"将图片写入缓存");

[self saveImage:tempImage

toCachePath:[PHOTOCACHEPATH stringByAppendingPathComponent:imageName]];

//创建uploadModel

NSLog(@"创建model");

uploadModel *model = [[uploadModel alloc] init];

model.path = [PHOTOCACHEPATH stringByAppendingPathComponent:imageName];

model.name = imageName;

model.type = @"image";

model.isUploaded = NO;

//将模型存入待上传数组

NSLog(@"将Model存入待上传数组");

[self.uploadArray addObject:model];

}

}

else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {

if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {

//如果是拍摄的视频, 则把视频保存在系统多媒体库中

NSLog(@"video path: %@", info[UIImagePickerControllerMediaURL]);

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

[library writeVideoAtPathToSavedPhotosAlbum:info[UIImagePickerControllerMediaURL] completionBlock:^(NSURL *assetURL, NSError *error) {

if (!error) {

NSLog(@"视频保存成功");

} else {

NSLog(@"视频保存失败");

}

}];

}

//生成视频名称

NSString *mediaName = [self getVideoNameBaseCurrentTime];

NSLog(@"mediaName: %@", mediaName);

//将视频存入缓存

NSLog(@"将视频存入缓存");

[self saveVideoFromPath:info[UIImagePickerControllerMediaURL] toCachePath:[VIDEOCACHEPATH stringByAppendingPathComponent:mediaName]];

//创建uploadmodel

uploadModel *model = [[uploadModel alloc] init];

model.path = [VIDEOCACHEPATH stringByAppendingPathComponent:mediaName];

model.name = mediaName;

model.type = @"moive";

model.isUploaded = NO;

//将model存入待上传数组

[self.uploadArray addObject:model];

}

//[picker dismissViewControllerAnimated:YES completion:nil];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

[picker dismissViewControllerAnimated:YES completion:nil];

}

以上所述是小编给大家介绍的iOS实现视频和图片的上传思路,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

php ios视频文件上传,iOS实现视频和图片的上传思路相关推荐

  1. 如何将大的视频文件压缩成小的视频文件?

    如何将大的视频文件压缩成小的视频文件?视频是我们在生活中不可或缺的一部分,随着制作视频的小伙伴越来越多,大家都想把制作好的视频上传到一些平台或传给别人,有时候我们会遇到视频内存过大的问题,今天我给大家 ...

  2. python读视频文件_python读取和保存视频文件

    如何用python实现视频关键帧提取并保存为图片?也许你会觉得对小编多做一点事你会觉得你很爽,可是在小编看来这是不屑的 import cv2vc = cv2.VideoCapture('Test.av ...

  3. 设置html视频文件音量默认,视频文件音量不一致 怎样调节视频音量

    当我们在后期剪辑拍摄的视频文件时,可能会遇到视频文件音量不一致的情况,由于拍摄的原因而导致的.所以在后期制作中就需要采取一定的措施啦.可以对视频文件音量不一致的文件进行调整,将音量调整至一致,那么怎样 ...

  4. 一个基于Vue的移动端多文件上传插件,支持常见图片的上传。

    特性 多文件上传 上传图片预览 上传状态监测 删除指定图片 清空图片 重新上传 安装 npm i vue-easy-uploader --save 使用 在入口文件main.js中加入以下代码: im ...

  5. mysql+视频文件转成流_视频文件自动转rtsp流

    最近碰到一个项目需要用到 rtsp 视频流做测试, 由于真实环境的 摄像头 并不能满足需求,故尝试了一下用本地视频文件转换成rtsp视频流做测试,记录一下~ 采用方案: Docker + EasyDa ...

  6. 前端头像上传功能实现之普通图片/头像上传 详细解析1【扩展知识FormData对象】

    上传的图片/头像有两种方案上传 第一种我们不对图片做处理直接上传到服务器端,把图片上传到服务器的img文件夹当中,然后我们把图片的地址信息存储在数据库当中,用图片的时候我们直接调用地址 第二种方案是我 ...

  7. linux opencv 显示视频文件夹,opencv cvCaptureFromFile读取视频问题汇总

    一.无法读取文件 报错: OpenCV报错: warning: Error opening file (../../modules/highgui/src/cap_ffmpeg_impl.hpp:52 ...

  8. Ubuntu系统下安装opencv3.x并打开图片和视频文件以及打开摄像头录制视频

    目录 一.安装opencv 1.前置安装条件 2.安装环境 3.下载opencv3.4.11 4.解压安装包 5.开始安装 6.检查是否安装成功 二.显示图片和播放视频 1.显示图片 2.播放视频 三 ...

  9. Jrtplib发送视频文件 + FFMPEG解码+VFW播放视频 (回调方式)

    在上篇文章<Jrtplib收发H264文件 + FFMPEG解码+VFW播放视频> 里,我们采用的模式是发送端读取本地H264文件, 把完整的Naul(包含起始码) 逐个发送给接收端,接收 ...

  10. OpenCV VideoCapture使用方法(视频文件、摄像头、网络视频文件)

    一.视频读取 cv::VideoCapture既支持视频文件的读取,也支持从摄像机中视频的读取.cv::VideoCapture对象的创建方式有以下三种: 方式一:     cv::VideoCapt ...

最新文章

  1. 配置Cesium编译环境
  2. 牛顿迭代法求解平方根
  3. html保存助手,HTML助手与HTML助手内
  4. 直播 | 同源共流:一个优化框架统一与解释图神经网络
  5. 苹果公司透露Siri新发音引擎的内部原理
  6. 用超 7500 万的 GitHub 代码仓库实力解读:哪门编程语言热度最高?
  7. java代码审计工具_Java代码审计汇总系列(六)——RCE
  8. 树莓派测试USB摄像头是否可用
  9. STM32F205 HAL库 RTC软件复位后不准
  10. 数据分析5大软件Excel、SAS、R、SPSS、Python优势分析
  11. gcj-02 wgs-84 java_GCJ-02火星坐标系和WGS-84坐标系转换关系
  12. 腾讯云云通信TLS后台API在mac上JAVA DEMO搭建
  13. webstorm 光标换行快捷键
  14. 使用代理服务器打不开网页_代理服务器:信息安全表象下的另一面
  15. 高分子材料老化的内外因、性能评价与预防措施
  16. redis的游标和模糊查询key的不适用
  17. 风口的猪(小米实习生招聘)
  18. 《袁老师访谈录》第十八期-百万对话(2):漫漫创业路
  19. Deep Learning(1)
  20. Python全栈 Linux基础之1.Linux初章

热门文章

  1. oracle 数据库里查看表空间使用状况
  2. ALFNet行人检测
  3. 对光照、阴影和反光具有鲁棒性的变化检测算法及实现
  4. attribute 'downsample' of type 'NoneType' is not usable in a script method
  5. 人脸质量评估网络推荐
  6. 'module' object is not callable
  7. 跨平台SSE、AVX指令测试
  8. oracle left join优化
  9. c语言中getc与gets,getc()和gets()的用法
  10. c语言结构体老师信息管理系统,C语言课程设计职工信息管理系统结构体数组实现程序源代码.doc...