(iOS开发) 往服务器上传视频

时间:2021-12-29 17:56:11

情景: 多选视频,然后打包成一个zip压缩包(里面有多个视频,一个json文件)

一、先生成本地的文件:

-(NSString *)getDocumentPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *dic = [NSHomeDirectory() stringByAppendingString:@"/Documents/ufile"];
    NSString * fileName =[NSString stringWithFormat:@"ufile.json"];
    BOOL isDic;
    if(![fileManager fileExistsAtPath:dic isDirectory:&isDic]||(!isDic))
    {
        [fileManager createDirectoryAtPath:dic withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString* filePath = [NSString stringWithFormat:@"%@/%@",dic,fileName];
    if (![fileManager fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager]createFileAtPath:filePath contents:nil attributes:nil];
    }

    return filePath;
}

二、生成json文件的时候的代码:

1、先自己生成个内容类似于son的NSMutableDictionary

2、将这个字典转换成NSData,写入到本地的文件中

 NSData * jsonData =[NSJSONSerialization dataWithJSONObject:[self createDataDic] options:NSJSONWritingPrettyPrinted error:&parseError];
    [jsonData writeToFile:jsonPath atomically:YES];
三、文件压缩:

1、

#import "ZipArchive.h"

2、压缩方法:

-(void)zip{
    
    BOOL isDir=NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *mypath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *file = [NSString stringWithFormat:@"%@/%@",mypath,@"ufile"];
    NSArray *subpaths = [fileManager subpathsAtPath:file];
//    NSLog(@"subpaths   %@",subpaths);
    NSString *archivePath = [mypath stringByAppendingString:[NSString stringWithFormat:@"/%@.zip",@"ufile"]];
    
    ZipArchive *archiver = [[ZipArchive alloc] init];
    [archiver CreateZipFile2:archivePath];
//    NSLog(@"ZIP archivePath的地址为: %@",archivePath);
    for(NSString *path in subpaths)
    {
        NSString *longPath = [file stringByAppendingPathComponent:path];
        if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && !isDir)
        {
            //注意newname的设置 也有可能是这样[NSString stringWithFormat:@"%@/%@",@"ufile",path]
            [archiver addFileToZip:longPath newname:path];
        }
    }
    //add kao 20130620
    //注释后添加
    [archiver CloseZipFile2];

}
 
特别要注意的是: newname的设置,有几种情况,正常情况下只需要直接将数组subpaths中的地址直接赋值就好。 


四: 上传到服务器:

/** *  功能 AFNetWorking带进度指示文件上传 *
 @param filePath 文件路径 */
-(void)uploadfile:(NSString *)filePath{
    
    NSMutableString *addstring;
    addstring=[NSMutableString stringWithFormat:@"http:///api/XXXXXX"];
    [addstring insertString:[[NSUserDefaults standardUserDefaults] objectForKey:HTTPmyAPI] atIndex:7];
    NSData *filedata=[NSData dataWithContentsOfFile:filePath];
    AFHTTPRequestOperationManager *mymanager=[AFHTTPRequestOperationManager manager];
    mymanager.requestSerializer = [AFJSONRequestSerializer serializer];
    [GetSomething setManager:mymanager time:[GetSomething getTimeNow] value:nil];
    [manager.requestSerializer setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
    [manager POST:addstring parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        [MBProgressHUD showMessage:nil];
        [formData appendPartWithFileData:filedata name:@"ufile" fileName:@"ufile.zip" mimeType:@"application/octet-stream"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject){
        [MBProgressHUD hideHUD];
        dispatch_async(dispatch_get_main_queue(), ^{
            MBProgressHUD * hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = KSetString(@"local_uploadsuccess");
            hud.removeFromSuperViewOnHide =YES;
            [hud hide:YES afterDelay:0.7f];
        });
        
        [self deleteLocalZipFile];

    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"上传失败");
        NSLog(@"%@",error);
        [MBProgressHUD hideHUD];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:KSetString(@"local_uploadfailed") message:nil delegate:nil cancelButtonTitle:KSetString(@"local_know") otherButtonTitles:nil];
        [alertView show];
        
        [self deleteLocalZipFile];
    }];

}

//删除本地的文件
-(void)deleteLocalZipFile
{
    //完成要删除
    [upLoadDataArray removeAllObjects];
    [classSelectedArray removeAllObjects];
    [self hide];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //移除文件夹
    NSString *dic = [NSHomeDirectory() stringByAppendingString:@"/Documents/ufile"];
    if ([fileManager fileExistsAtPath:dic]) {
        //        NSLog(@"移除文件夹 %@",dic);
        [fileManager removeItemAtPath:dic error:nil];
    }
    
    //移除zip包
    NSString *mypath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *archivePath = [mypath stringByAppendingString:[NSString stringWithFormat:@"/%@.zip",@"ufile"]];
    if ([fileManager fileExistsAtPath:archivePath]) {
        [fileManager removeItemAtPath:archivePath error:nil];
    }
    
    
}

这边的上传的参数为nil,具体的设置每个人都不同,所以你们自己解决就好了~~