IOS开发教程 - 如何通过二进制数据上传图片

在项目中,我们经常会遇到图片上传的问题,估计大家都会遇到这个问题,今天特意总结并贴出实用的代码分享给大家。希望对大家有所帮助。

直接上代码:

-(NSString *)uploadImage: (NSString *)url
                     postParems: (NSMutableDictionary *)postParems
                          image: (UIImage *)image
{
    NSString *TWITTERFON_FORM_BOUNDARY = @"--WebKitFormBoundaryqRL9PfS8f0kLqJF0";
    //根据url初始化request
    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];
    //得到图片的data
    NSData *data = UIImagePNGRepresentation(image);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [postParems allKeys];
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //添加分界线,换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //添加字段名称,换2行
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        //添加字段的值
        [body appendFormat:@"%@\r\n",[postParems objectForKey:key]];
        NSLog(@"添加字段的值==%@",[postParems objectForKey:key]);
    }
    ////添加分界线,换行
    [body appendFormat:@"%@\r\n",MPboundary];
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"file",@"filename.jpg"];
        //声明上传文件的格式
        [body appendFormat:@"Content-Type: image/jpg,image/png, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n"];
    //声明结束符:
    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];
    //加入结束符
    [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:@"%ld", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];

    NSHTTPURLResponse *urlResponese = nil;
    NSError *error = [[NSError alloc] init];
    NSData *resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponese error:&error];
    NSString *result= [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    if([urlResponese statusCode] >=200 && [urlResponese statusCode] < 300)
    {
        NSLog(@"返回结果=====%@",result);
        return result;
    }
    return nil;
}


在调用的地方调用一下代码

    NSMutableDictionary * dict=[NSMutableDictionary dictionaryWithCapacity:7];
    [dict setValue:@"value123" forKey:@"key123"];
    NSString *url = @"http://192.168.1.150/upload/fileUpload.do";
    UIImage *image = [UIImage imageNamed:@"upimage"];
    [self uploadImage:url postParems:dict image:image];

你可能感兴趣的:(IOS)