AFNetworking 2.0上傳圖片

github 下載demo:https://github.com/MartinLi841538513/MartinDemos (一切以demo爲準)php

1,上傳圖片git

這裏注意到,AFNetworking 2.0和以前的版本的使用是不同的,我這裏介紹2.0之後版本的使用,我這我的就是這樣,喜歡偏向於用新的。github

    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,那麼恭喜你,你上傳成功了。服務器

 

上傳多張圖片:app

    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];

注意後臺接收圖片的方式。ide

相關文章
相關標籤/搜索