iOS 图片以文件形式上传到服务器

如果调用相机,相册请查看这里:
http://www.jianshu.com/p/4384efc6fb04

调用上传图片方法

 [self postRequestWithURL:@"URL地址" picFileName:@"boris.png" dataimage:@"相册或相机返回的图片" andparameters:@"请求的参数(例如用户id)" andBlock:^(NSDictionary * _Nonnull retDic, NSError * _Nonnull error) {
            if ((YES)) {
             //请求成功
            }
        }];
#pragma makr -- 上传图片到服务器
static NSString * const FORM_FLE_INPUT = @"file";//字段名  根据接口命名
-(void)postRequestWithURL: (NSString *)url picFileName: (NSString *)picFileName
 dataimage:(UIImage *)image andparameters:(NSMutableDictionary *) dic
 andBlock:(void(^)(NSDictionary *retDic,NSError *error))block
{
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:
    [NSURL URLWithString:url]   cachePolicy:
    NSURLRequestReloadIgnoringLocalCacheData   timeoutInterval:10];

    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];

    NSData* data;
    NSMutableString *body=[[NSMutableString alloc]init];
   //参数的集合的所有key的集合,注意此处,注意此处
   NSArray *keys = @[@"file",@"P"];

    //遍历keys
    for(int i=0;i<[keys count];i++){
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是imgfile,说明value是字符类型,比如name:Boris
        if(![key isEqualToString:@"file"])
        {
            //得到当前key
            NSString *key=[keys objectAtIndex:i];
            //添加分界线,换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称,换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            NSData *datadic=[NSJSONSerialization 
            dataWithJSONObject:dic   options:NSJSONWritingPrettyPrinted error:nil];
            NSString *jsonStr=[[NSString alloc]initWithData:datadic encoding:NSUTF8StringEncoding];
            [body appendFormat:@"%@\r\n",jsonStr];
        }
    }
    //添加文件
    [body appendFormat:@"%@\r\n",MPboundary];
 
    //声明pic字段,文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\";
    filename=\"%@\"\r\n",FORM_FLE_INPUT,picFileName];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type:image/png\r\n\r\n"];
 
    //声明结束符:--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData,用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    [request setHTTPMethod:@"POST"];
    [NSURLConnection sendAsynchronousRequest:request  queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            NSDictionary* json = [NSJSONSerialization
                                  JSONObjectWithData:data
                                  options:kNilOptions
                                  error:&connectionError];
            block(json,nil);
        }else{
            block(nil,connectionError);
        }
    }];
}

这段代码如有雷同,是我抄袭,我也不知道抄的哪;

你可能感兴趣的:(iOS 图片以文件形式上传到服务器)