首页 > 其他分享 >iOS开发之利用web表单上传媒体资源(照片/视频)

iOS开发之利用web表单上传媒体资源(照片/视频)

时间:2022-11-28 17:07:23浏览次数:71  
标签:web NSUTF8StringEncoding iOS dataUsingEncoding stringWithFormat 表单 NSString body


之前公司的Java工程师比较厉害,所以我在前端上传一个通过编码的NSString或者NSData类型的数据,就可以上传成功,现在因为此Java工程师没做过,所以为了实现类似于发布照片或小视频这样的功能,不得已将内容以表单的形式上传,实现发布的功能。

       同时要记住,后台Java代码,其他的参数可以通过参数名获取值,资源内容可以直接通过MusultFile形式进行接收即可,这样就会直接生成一个资源文件,然后可以上传云端生成一个url地址,方便前端资源展示。

       下面展示Demo中的代码:也会附上我实际应用的部分代码,具体大家自行研究,有问题请留言,不喜勿喷~

//请求方法
-(void)method4{
    NSURL *uploadURL = [NSURL URLWithString:@"http://192.168.124.233/report/addReportTest"];
    NSLog(@"请求路径为%@",uploadURL);//接口路径:根据自己的需要修改
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        
        //body
        NSData *body = [self prepareDataForUpload];
        
        //request
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
        [request setValue:@"BBH" forHTTPHeaderField:@"User-Agent"];
        [request setValue:@"max-age=7200" forHTTPHeaderField:@"Cache-Control"];
        
        //设置上传数据的长度及格式
        [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)body.length]forHTTPHeaderField:@"Content-Length"];
        
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:body];
        
        NSURLSession *session = [NSURLSession sharedSession];
        
        NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
            
            NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"message: %@", message);
            
            [session invalidateAndCancel];
        }];
        
        [uploadTask resume];
    });
}
//生成bodyData
-(NSData*) prepareDataForUpload
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *uploadFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    //NSLog(@"documen   %@",uploadFilePath);
    NSString *lastPathfileName = [uploadFilePath lastPathComponent];
    NSMutableData *bodyData = [NSMutableData data];
    NSData *dataOfFile = [[NSData alloc] initWithContentsOfFile:uploadFilePath];
    
    NSDictionary *paramDic = @{@"userId":@"1234",@"content":@"哈哈",@"isPublic":@"0",@"fileType":@"0"};
    
    [paramDic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL *_Nonnull stop) {
        
        NSString *boundry1 = [NSString stringWithFormat:@"--%@\r\n",boundary];
        
        [bodyData appendData:[[NSString stringWithFormat:@"%@", boundry1] dataUsingEncoding:NSUTF8StringEncoding]];
        
        NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",key];
        NSLog(@"%@",disposition);
        [bodyData appendData:[[NSString stringWithFormat:@"%@", disposition] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[[NSString stringWithFormat:@"%@", obj] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }];
    
    if (dataOfFile) {
        //连续上传相同的三张图片
        [bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data;  name=\"%@\"; filename=\"%@\"\r\n", fileParam, lastPathfileName] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:dataOfFile];
        [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParam, lastPathfileName] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:dataOfFile];
        [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParam, lastPathfileName] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:dataOfFile];
        [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [bodyData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    return bodyData;
}

我项目中实际修改的代码样式:

#pragma mark ---- 利用 web表单的形式 上传图片或小视频 参数一:url地址;参数二:0:照片,1:视频;参数三:媒体数组;参数四:其他参数字典集合
+(void)uploadWebFormWithUrlStr:(NSString *)urlStr mediaType:(NSString *)type mediaArray:(NSArray *)array param:(NSDictionary *)paramDic complete:(void(^)(id))complete
{
    if ([self isConnectionAvailable]) {
        NSURL *uploadURL = [NSURL URLWithString:urlStr];
        //NSLog(@"请求路径为%@",uploadURL);
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
            
            //body
            NSData *body = [self prepareDataForUploadWithArray:array param:paramDic mediaType:type];
            
            //request
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
            [request setValue:@"BBH" forHTTPHeaderField:@"User-Agent"];
            [request setValue:@"max-age=7200" forHTTPHeaderField:@"Cache-Control"];
            
            //设置上传数据的长度及格式
            [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",WEB_BOUNDARY]forHTTPHeaderField:@"Content-Type"];
            [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)body.length]forHTTPHeaderField:@"Content-Length"];
            
            [request setHTTPMethod:@"POST"];
            [request setHTTPBody:body];
            
            NSURLSession *session = [NSURLSession sharedSession];
            
            NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
                
                NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
                //NSLog(@"message: %@", resultDic);
                complete(resultDic);
                
            }];
            //[session invalidateAndCancel];
            [uploadTask resume];
        });
    }else{
        //complete(nil);
        [SVProgressHUD showErrorWithStatus:@"无网络/网络不可用"];
    }
}
//生成bodyData
+(NSData*) prepareDataForUploadWithArray:(NSArray *)array param:(NSDictionary *)paramDic mediaType:(NSString *)type
{
    NSMutableData *bodyData = [NSMutableData data];
    
    //其他参数字典集合
    [paramDic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL *_Nonnull stop) {
        
        NSString *boundry1 = [NSString stringWithFormat:@"--%@\r\n",WEB_BOUNDARY];
        [bodyData appendData:[[NSString stringWithFormat:@"%@", boundry1] dataUsingEncoding:NSUTF8StringEncoding]];
        NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",key];
        //NSLog(@"%@",disposition);
        [bodyData appendData:[[NSString stringWithFormat:@"%@", disposition] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[[NSString stringWithFormat:@"%@", obj] dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }];
    
    //媒体添加
    for (ACMediaModel *acMediaM in array) {
        NSData *dataOfFile = [[NSData alloc] initWithData:acMediaM.uploadType];
        if (dataOfFile) {
            [bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", WEB_BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
            [bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data;  name=\"%@\"; filename=\"%@\"\r\n", WEB_FILEPARAM, acMediaM.name] dataUsingEncoding:NSUTF8StringEncoding]];
            [bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [bodyData appendData:dataOfFile];
            [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            
            if ([type isEqualToString:@"1"]) {
                //添加视频图片
                NSData *imgOfFile = UIImageJPEGRepresentation(acMediaM.image, 0.5);
                
                [bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", WEB_BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
                [bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data;  name=\"%@\"; filename=\"%@\"\r\n", WEB_FILEPARAM, @"video.png"] dataUsingEncoding:NSUTF8StringEncoding]];
                [bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
                [bodyData appendData:imgOfFile];
                [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            }
        }
    }
    
    [bodyData appendData:[[NSString stringWithFormat:@"--%@--\r\n", WEB_BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
    
    return bodyData;
}

​源码下载:https://github.com/hbblzjy/iOSuploadFileWithWebForm​


标签:web,NSUTF8StringEncoding,iOS,dataUsingEncoding,stringWithFormat,表单,NSString,body
From: https://blog.51cto.com/u_15894905/5892241

相关文章

  • iOS开发之使用block块进行数据遍历的方法
    看了一篇文章,发现遍历数组、字典中的数据时,除了使用for循环外,还可以使用block块进行操作,瞬间感觉iOS的语言代码确实有点高大上的感觉,下面就简单的介绍一下这个方法。首先是......
  • iOS开发之自定义ActionSheet视图
    有时我们需要用到actionSheet来展示,但是但是往往系统的界面显示很丑或者并不符合UI的要求,所以在这里自定义一个,方便以后使用,后续有时间写一下Swift的开发。自定义ActionShee......
  • iOS模仿京东商城中的选择地区样式
    在ViewController文件中创建添加地址界面:@property(nonatomic,strong)UILabel*selectAreaLabel;//地区显示@property(nonatomic,strong)UITextField*nameTextF;//收货人......
  • IOS中的数据存储方式,特点,使用情况
    数据存储的核心都是写文件,主要有四种持久化方式:属性列表(Plist),对象序列化,SQLite数据库,CoreData。存储Plist:     键值进行存储,不能存储对象。对象需要序列化编码才能......
  • iOS开发之样式多样好用的滑动视图Demo
    现在App基本上都有滑动式图的展示,尤其是新闻资讯类的用到的最多,今天就给大家展示一个多样的滑动视图样式;首先可以看到,这是几种不同的搭配模式,也可以根据style进行其他样式的......
  • iOS开发之可双向调节的Slider滑块
    滑块在很多地方都有使用,所以这里向大家展示一个自定义的可双向控制的Slider,并且可以通过代理方法获取相应的范围值,部分代码如下:属性值:/** 设置最小值 */@property(nonato......
  • Swift基础之封装一个WebViewController
    研究了一段时间,总算搞定了这个功能封装,现在给大家分享一下,具体看代码,上面有对应的文字描述,有问题请留言,下载源码,请帮忙点一下star,给点继续分享的动力,谢谢~/**//swift中......
  • iOS开发之最近的小知识点总结一
    1、NSInteger打印以及字符串的转换2、UIScrollView在iOS7中使用了Autolayout导致不能滚动3、APP包瘦身4、interactivepopgesturerecognizer使用5、UICollectionView的数......
  • iOS开发之模仿语音聊天时,显示的音量图
    因为项目中有涉及到语音的内容,所以在这里实现一下说话时语音的音量图的展示具体内容查看代码,有注释语音内容的工具类:staticidinstance;#pragmamark-单例+(instancetyp......
  • iOS开发之最近小知识总结二
    有好多都是基础知识,仅供参考,谢谢1、autolayout自动布局autoLayout需要在​​-(void)viewDidLoad​​​方法执行完后生效,所以需要在​​-(void)viewDidAppear:(BOOL)ani......