如何通过AFNetworking上传文件并发布多个参数?

时间:2015-04-06 07:25:04

标签: ios afnetworking

我正在学习如何使用AFNetworking for iOS。我经常使用ASIHttprequest上传文件并同时发布多个参数,使用ASIHttprequest这样很简单。

[request setPostValue:distanceLabel.text forKey:@"km"];
[request setPostValue:speedValue forKey:@"speed"];
[request setFile:filePath forKey:@"filedata"];

我对AFNetworking有很多了解,但我不知道该怎么做。请告诉我代码。谢谢!

3 个答案:

答案 0 :(得分:1)

请尝试以下代码: -

我已将此代码与图像一起使用。您也可以尝试使用其他文件类型。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSData *imageData = UIImageJPEGRepresentation(aDict[@"Image"], 0.5);

AFHTTPRequestOperation *op = [manager POST:aStrURL parameters:aDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:myParamName fileName:@"photoNew.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];

答案 1 :(得分:0)

组合一个键的多个查询值。

如果您使用NSDictionary + NSSet,则会从NSArray获得没有[]的查询网址。

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:[NSSet setWithObjects:@"value1", @"value2", nil], @"myKey", nil];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSURLRequest *request = [httpClient requestWithMethod:@"GET" path:@"/path" parameters:params];

NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filename = [documentsDirectory stringByAppendingPathComponent:photoName];
NSData *imageData = [NSData dataWithContentsOfFile:filename];
[formData appendPartWithFileData:imageData
                            name:@"files"
                        fileName:photoName mimeType:@"image/jpeg"];

答案 2 :(得分:0)

https://github.com/AFNetworking/AFNetworking有很好的例子, 我在这里如何使用这些东西 1.创建您的客户端实例,每次需要连接到服务器时都会为应用程序提供服务

file.h

#import "AFHTTPRequestOperationManager.h"

@interface YourClient : AFHTTPRequestOperationManager

+ (instancetype)sharedClient;
- (void)send_Image_POST_WS:(NSString *)ws_name image:(NSData*)imageData param:(NSDictionary *)param :(void (^)(NSDictionary *json, NSError *error, NSInteger status))block;

file.m

static NSString * const YouBaseURLString = @"http://blablabla";
@implementation YourClient


+ (instancetype)sharedClient {

    static YourClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[YourClient alloc] initWithBaseURL:[NSURL YouBaseURLString]];
        _sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

     });

    return _sharedClient;
}

// you can change the block according to the needs of its receiver

- (void)send_Image_POST_WS:(NSString *)ws_name image:(NSData*)imageData param:(NSDictionary*)param :(void (^)(NSDictionary *json, NSError *error, NSInteger status))block{

     // NSLog(@“WS: %@\nPARAMS: --> %@",ws_name,[param description]);

    [self POST:ws_name parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileData:imageData name:@"imagedata" fileName:@"imagedata.png" mimeType:@"image/png"];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (block) {
           // NSLog(@"WS:%@\nRESPONSE : -> %@",ws_name,responseObject);
            block(responseObject,nil,operation.response.statusCode);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

         //NSLog(@"Response error text %@",operation.responseString);
       // you can display here alert
        if (block) {
            block(nil,error,operation.response.statusCode);
        }
    }];
 }
  1. 必须发送图像的类
  2. ProfileViewController.m

    -(void)send_UploadImage:(UIImage *)image{
    
    // here you can activate a spinner (use which one you want - of Apple or some open source)  
        NSDictionary *params = @{@"extension":@"png",
                                 @“usr_id”:@“1”};// <<<—— this is an additional data the service on the server side will need, just example, replace with needed
    
        NSData *dataImage = UIImageJPEGRepresentation(image, 0.5);
    // @"common/upload_image" replace with your path to the service on the server side, it will be added to the Base URL
    
        [[YourClient sharedClient] send_Image_POST_WS:@"common/upload_image" image:dataImage param:params :^(NSDictionary *json, NSError *error) {
    
            // hide spinner
    
            if (!error) {
            // read json, change UI here you are on the main thread    
    
    
            }else{
              // react accordingly main thread
            }
        }];
    }