技术文章分类(180)

技术随笔(11)

AFNetworking 2.0上传图片

github 下载demo:https://github.com/MartinLi841538513/MartinDemos (一切以demo为准)

1,上传图片

这里注意到,AFNetworking 2.0和之前的版本的使用是不一样的,我这里介绍2.0以后版本的使用,我这个人就是这样,喜欢偏向于用新的。

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.greenwh.com"]];
    NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"testImg1.png"], 0.5);
    NSDictionary *parameters = @{@"mid": @"70"};
    AFHTTPRequestOperation *op = [manager POST:@"/wap.php/Member/head" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //do not put image inside parameters dictionary as I did, but append it!
        //这里的name是服务器接收图片的字段。
        [formData appendPartWithFileData:imageData name:@"picture" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@ ***** %@", operation.responseString, error);
    }];
    [op start];

如果打印出得status等于2,那么恭喜你,你上传成功了。

 

上传多张图片:

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.greenwh.com"]];
    NSData *imageData1 = UIImageJPEGRepresentation([UIImage imageNamed:@"testImg1.png"], 0.5);
    NSData *imageData2 = UIImageJPEGRepresentation([UIImage imageNamed:@"testImg2.png"], 0.5);
    NSArray *imgs = [NSArray arrayWithObjects:imageData1,imageData2, nil];
    NSDictionary *parameters = @{@"mid": @"70",@"sid":@"6",@"title":@"标题1",@"content":@"内容1",@"degree":@"8",@"price":@"20",@"name":@"martin1",@"mobile":@"18613961267"};
    AFHTTPRequestOperation *op = [manager POST:@"/wap.php/Second/transrelease" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //do not put image inside parameters dictionary as I did, but append it!
        //这里的name是服务器接收图片的字段。
        for (int i; i<imgs.count; i++) {
            [formData appendPartWithFileData:imageData1 name:[NSString stringWithFormat:@"picture[%d]",i] fileName:[NSString stringWithFormat:@"photo%d.jpg",i] mimeType:@"image/jpeg"];
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@ ***** %@", operation.responseString, error);
    }];
    [op start];

注意后台接收图片的方式。

posted @ 2014-12-11 21:30  坤哥MartinLi  阅读(415)  评论(0编辑  收藏  举报