iOS 图片视频上传服务器

    xiaoxiao2026-03-17  11

         项目新增需求,需要用户把手机里的视频和图片上传,焦头烂额弄了三天,总算是实现功能了。于是记下实现代码,对于刚做视频这方面的或许有点帮助吧,也让自己以后有需要了还可以回过头看一看。做iOS几个月了,做明显的感受是,大牛真的是大牛,想成为大牛就得一步一个脚印,虚心求教,埋头苦干,不说了,代码奉上。

    - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

    {

        NSLog(@"buttonIndex = [%ld]",buttonIndex);

        switch (buttonIndex) {

            case 0://照相机

            {                 UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

                imagePicker.delegate = self;

                imagePicker.allowsEditing = YES;

                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

                imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: (NSString *) kUTTypeImage, nil];

                [self presentModalViewController:imagePicker animated:YES];

                

            }

                break;

            case 1://摄像机

            {

                AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

                if (authStatus == AVAuthorizationStatusRestricted

                    || authStatus == AVAuthorizationStatusDenied) {

                    NSLog(@"摄像头已被禁用,您可在设置应用程序中进行开启");

                    return;

                }

                

                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

                    UIImagePickerController *picker = [[UIImagePickerController alloc] init];

                    picker.delegate = self;

                    picker.allowsEditing = YES;

                    picker.sourceType = UIImagePickerControllerSourceTypeCamera;

                    picker.videoQuality = UIImagePickerControllerQualityType640x480; //录像质量

                    picker.videoMaximumDuration = 5 * 60.0f; // 限制视频录制最多不超过5分钟

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

                    [self presentViewController:picker animated:YES completion:NULL];

    //                self.shouldAsync = YES;

                } else {

                    NSLog(@"手机不支持摄像");

                }

                

            }

                break;

            case 2://本地相簿

            {

                UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

                imagePicker.delegate = self;

                imagePicker.allowsEditing = YES;

                imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

                imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: (NSString *) kUTTypeImage, nil];

                [self presentModalViewController:imagePicker animated:YES];

                

            }

                break;

            case 3://本地视频

            {

                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

                    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];

                    imagePicker.videoQuality =UIImagePickerControllerQualityTypeIFrame960x540;//视频质量设置

                    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

                    imagePicker.delegate = self;

                    imagePicker.allowsEditing = YES;

                    imagePicker.videoMaximumDuration = 300.0f;//设置最长录制5分钟

                    imagePicker.mediaTypes = [NSArray arrayWithObject:@"public.movie"];

                    [self presentModalViewController:imagePicker animated:YES];

                    

                }

            }

            case 4://本地音频

            {

                

                

            }

                break;

            default:

                break;

        }

    }

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

        

        NSString *type = [info objectForKey:UIImagePickerControllerMediaType];

        

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

            

            UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

            CGSize imagesize = image.size;

            imagesize.height =626;

            imagesize.width =413;

            //对图片大小进行压缩--

            image = [self imageWithImage:image scaledToSize:imagesize];

            

            NSData *data;

            if (UIImagePNGRepresentation(image) == nil){

                data = UIImageJPEGRepresentation(image, 1.0);

            }

            else

            {

                data = UIImagePNGRepresentation(image);

            }

            

            //图片保存的路径

            //这里将图片放在沙盒的documents文件夹中

            NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

            

            //文件管理器

            NSFileManager *fileManager = [NSFileManager defaultManager];

            

            //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png

            [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];

            [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];

            

            //得到选择后沙盒中图片的完整路径

            NSString  *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];

            NSData *imgData = [NSData dataWithContentsOfFile:filePath];

                   NSString *str = @"XXXXXXXXXXXXXXXX";

                    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    //        [manager setRequestSerializer:[AFXMLParserResponseSerializer  serializer]];

                manager.responseSerializer = [AFHTTPResponseSerializer serializer];

            [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

            [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

            

            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];

            

            [manager POST:str parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

                [formData appendPartWithFileData:imgData name:@"Filedata"fileName:@"test.jpg"mimeType:@"image/jpg"];

            }success:^(AFHTTPRequestOperation *operation,id responseObject) {

                // upload succ

                NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

                NSLog(@"%@",str);

                

                

                

            }failure:^(AFHTTPRequestOperation *operation,NSError *error) {

                NSLog(@"#######upload error%@", error);

            }];

        }else if ([type isEqualToString:@"public.movie"]){

            

            // 如果是视频

            NSURL *url = info[UIImagePickerControllerMediaURL];

            // 获取视频总时长

            CGFloat lengthTime = [self getVideoLength:url];

            NSLog(@"%f",lengthTime);

            // 保存视频至相册 (异步线程)

            NSString *urlStr = [url path];

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                

                if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {

                    

                    UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);

                }

                

            });

            

            //转换时文件不能已存在,否则出错

            AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];

            NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];

            if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {

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

                NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名,以免重复,在测试的时候其实可以判断文件是否存在若存在,则删除,重新生成文件即可

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

                NSString* resultPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]];

                NSLog(@"%@",resultPath);

                exportSession.outputURL = [NSURL fileURLWithPath:resultPath];

                exportSession.outputFileType = AVFileTypeMPEG4;

                [exportSession exportAsynchronouslyWithCompletionHandler:^(void)

                 {

                     

                     if (exportSession.status == AVAssetExportSessionStatusCompleted) {

                         

                         

    //                     NSData *videoData = [NSData dataWithContentsOfURL:exportSession.outputURL];

    //                     AVPlayer *player = [AVPlayer playerWithURL:exportSession.outputURL];

    //                     AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];

    //                     playerLayer.frame = self.view.bounds;

    //                     [self.view.layer addSublayer:playerLayer];

    //                     [player play];

                         AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

                         NSString *str = @"xxxxxxxxxx";

                         //formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体

                         [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

                         [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

                         manager.responseSerializer = [AFHTTPResponseSerializer serializer];

                         [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"application/json", @"application/x-www-form-urlencoded", nil]];

                         [manager POST:str parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

                             

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

                             // 设置时间格式

                             //                NSLog(@"%@",videoData);

                             formatter.dateFormat = @"yyyyMMddHHmmss";

                             NSString *str = [formatter stringFromDate:[NSDate date]];

                             NSString *fileName = [NSString stringWithFormat:@"%@.mov", str];

    //                         [formData appendPartWithFileData:videoData name:@"Filename" fileName:fileName

    //                                                 mimeType:@"video/quicktime"];

                             [formData appendPartWithFileURL:exportSession.outputURL name:@"Filedata" fileName:fileName mimeType:@"video/quicktime" error:nil];

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

                             

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

                             

                             NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

                             NSLog(@"%@",str);

                             

                             

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

                             

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

                             

                         }];

                     }

                     

                 }];

            }

            

    //            NSDictionary *dict = @{@"username":@"syl"};

                /*

                 @param url 服务器地址

                 @param parameters 字典 token

                 @param fileData 要上传的数据

                 @param name 服务器参数名称 后台给你

                 @param fileName 文件名称 图片:xxx.jpg,xxx.png 视频:video.mov

                 @param mimeType 文件类型 图片:image/jpg,image/png 视频:video/quicktime

                 @param style 返回的数据类型

                 @param progress

                 @param success

                 @param failure

                 

                 

                

            

            

            }

        }

        

        

        [self dismissModalViewControllerAnimated:YES];

    }

    转载请注明原文地址: https://ju.6miu.com/read-1308068.html
    最新回复(0)