码迷,mamicode.com
首页 > 移动开发 > 详细

ios实战-上传图片到服务器

时间:2015-04-22 14:03:55      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

当然如果你的项目大的话最好使用开源的网络库ASI或者AFNetWork,库里面都有现有的方法,

如果你觉得就是想自己写一个,看这里

- (NSMutableURLRequest *)PostImageRequest:(NSString *)URLString
                                  UIImage:(UIImage*)image
                               parameters:(NSDictionary *)parameters
                                  success:(void (^)(id))success
                                  failure:(void (^)(NSError *))failure
{
    _success = success;
    _failure = failure;
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //得到图片的data
    NSData* data = UIImageJPEGRepresentation(image, 1);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [parameters allKeys];

    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic,说明value是字符类型,比如name:Boris
        if(![key isEqualToString:@"pic"])
        {
            //添加分界线,换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称,换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[parameters objectForKey:key]];
        }
    }

    ////添加分界线,换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段,文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"ImageField\"; filename=\"x1234.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/jpeg\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:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [_request setHTTPBody:myRequestData];
    //http method
    [_request setHTTPMethod:@"POST"];
    
    return _request;
}
- (void)start
{
    if (_request) {
        _urlConnection = [[NSURLConnection alloc]initWithRequest:_request delegate:self];
    }
    _request = nil;
}

- (void)syncStart
{
    if (_request) {
        NSError *error;
        NSData *returnData = [NSURLConnection sendSynchronousRequest:_request returningResponse:nil error:&error];
        if (!error) {
            NSString *receiveStr = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
            _success(receiveStr);
        } else {
            _failure(error);
        }
    }
    _request = nil;
}
#pragma mark ---- NSURLConnectionDataDelegate -----
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
    //NSLog(@"%@",[res allHeaderFields]);
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_responseData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *receiveStr = [[NSString alloc]initWithData:_responseData encoding:NSUTF8StringEncoding];
    _success(receiveStr);
}

#pragma mark ---- NSURLConnectionDelegate -----
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    _failure(error);
}

使用方法:

[httpManager PostImageRequest:UploadImageUrl
                          UIImage:image
                       parameters:params
                          success:^(id msg) {
                              debugLog(@"upload image success:%@", msg);
                              success(msg);
                         
                          } failure:^(NSError *error) {
                              failure(error);
                          }];
    
    [httpManager start];

NSURLConnection的使用方法就不细说了,查看查询文档或者到网上找

ios实战-上传图片到服务器

标签:

原文地址:http://my.oschina.net/iq19900204/blog/405028

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!