如何在上传带参数的图像时使用 AFNetworking 2.0 设置 cookie?

Posted

技术标签:

【中文标题】如何在上传带参数的图像时使用 AFNetworking 2.0 设置 cookie?【英文标题】:How can I set cookies with AFNetworking 2.0 while uploading image with parameters? 【发布时间】:2013-11-25 13:43:21 【问题描述】:

如果我必须在 post 请求中附加 cookie 怎么办?我该怎么做?

NSURL *URL = [NSURL URLWithString:addAddressUrl]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
     
// Set cookie too 
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"<URL>"]]; 
NSDictionary *cookiesDictionary = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; 

if(cookiesDictionary)  
    [request setAllHTTPHeaderFields:cookiesDictionary]; 

如何通过 AFNetworking 调用附加此请求?我浏览了 AFNetworking 的文档,但它没有解释如何在请求中使用其管理器对象设置 cookie。

如果我以某种方式将此 cookie 附加到内部的 afnetworking 文件中,我仍然无法上传图像。我尝试了两种可能的方法:

第一种方式:

-(void)uploadPrescriptionImage :(UIImage *)imagePresc

    // upload image here on the prescription
    /*
     Uploading a prescription
     URL: <URL>
     Params: <PARAMS>
     Method: POST
     */
    
    
    NSData *imageData = UIImageJPEGRepresentation(imagePresc, 1.0);
    
    NSString *orderID = [[NSUserDefaults standardUserDefaults] valueForKey:@"orderId"]; // orderId
    
    NSDictionary *parameters = @@"docName":prescriptionCell.doctorNameTextField.text,@"patientName":prescriptionCell.patientNameTextField.text,@"orderId" : orderID;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:@"<URL>" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     
        [formData appendPartWithFileData:imageData name:@"prescription" fileName:@"prescription" mimeType:@"image/jpeg"];
    
          success:^(AFHTTPRequestOperation *operation, id responseObject)
    
        NSLog(@"response is :  %@",responseObject);
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
    
        NSLog(@"Error: %@ *****", [error description]);
    ];

我在下面的afnetworking方法中附加了cookie:

- (AFHTTPRequestOperation *)POST:(NSString *)URLString
                      parameters:(NSDictionary *)parameters
       constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"<URL>"]];
    NSDictionary *cookiesDictionary = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    if (cookiesDictionary) 
        [request setAllHTTPHeaderFields:cookiesDictionary];
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];

    return operation;

第二种方式:

    NSDictionary *parameters = @@"docName":@"rr",@"patientName":@"tt",@"orderId" : @"1";
    
    
    NSString *URLString = @"<URL>";
//
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//
    NSURL *URL = [NSURL URLWithString:URLString];
    NSMutableURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    // Set cookie too
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"<URL>"]];
    NSDictionary *cookiesDictionary = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    if (cookiesDictionary) 
        [request setAllHTTPHeaderFields:cookiesDictionary];
    
//
//    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePathOfImage] progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error)
    
        if (error) 
            NSLog(@"Error: %@", error);
         else 
            NSLog(@"Success: %@ %@", response, responseObject);
        
    ];
    [uploadTask resume];

但是我不知道如何在这个请求中添加参数。我更喜欢第二种方式。

【问题讨论】:

【参考方案1】:

能够解决它..我只用第一种方式使用它..可能两种方式都可以使用:

这是我如何使用 afnetworking 2.0 上传图像的代码:

NSString *fileName = [NSString stringWithFormat:@"Prescription%d.jpg", counter];

    NSData *imageData = UIImageJPEGRepresentation(imagePresc, 1.0);

    NSString *orderID = [[NSUserDefaults standardUserDefaults] valueForKey:@"orderId"]; // orderId

    NSDictionary *parameters = @@"docName":prescriptionCell.doctorNameTextField.text,@"patientName":prescriptionCell.patientNameTextField.text,@"orderId" : orderID;

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:@"http://staging.healthkartplus.com/webservices/prescription/upload" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];

    success:^(AFHTTPRequestOperation *operation, id responseObject)
     
         NSLog(@"response is :  %@",responseObject);
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     
         NSLog(@"Error: %@ *****", [error description]);
     ];

这段代码的重要部分是:

[formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];

在上面的代码行中,您需要准确指定参数的名称和参数的类型(图像)。这里必须将“file”参数传递给它(根据我从服务器端获得的 API),类型应该是“image/jpeg”(或 image/pdf 或我认为是 image/png)。您可以为文件名传递任何名称,这里我将文件名传递为:NSString *fileName = [NSString stringWithFormat:@"Prescription%d.jpg", counter];

我做的唯一错误是我没有为图像指定正确的参数,总结一下我应该像这样发送它:

参数键:“文件” 数据:“文件或图像数据” 文件名:“.jpg”//注意:扩展名 图片名称必须在那里 mime 类型:“”

【讨论】:

以上是关于如何在上传带参数的图像时使用 AFNetworking 2.0 设置 cookie?的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 中上传带参数的图像

在IOS中上传带参数的多部分图像

当我尝试上传带口罩的图像时,认知面部检测不起作用

如何使用 alamofire 和数组形式的参数上传图像

AFNetworking 上传带参数的图片

使用 FineUploader 上传多个带索引的文件