通过POST方法ios将图像上传到服务器

时间:2016-06-02 11:46:21

标签: ios objective-c nsurlsession nsurlsessionuploadtask

我想通过post方法将图片上传到服务器。格式应该与["ImageName"=Image]类似。我尝试了以下代码,但它没有将图像上传到服务器。任何人都可以帮助我吗?

-(void)SaveImageToServer:(UIImage*)getImage :(NSString*)imageName :(NSString*)getUrlToSaveImg withCompletionBlock:(void(^)(NSMutableArray *))completionBlock
{
     NSMutableArray *arrrrr=[[NSMutableArray alloc]init];
     NSMutableURLRequest *reqqq=[[NSMutableURLRequest alloc]initWithURL: [NSURL URLWithString:getUrlToSaveImg]];
     NSData *dataOfImg=UIImagePNGRepresentation(getImage);
     NSString *stringImage = [dataOfImg base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
     NSString *concat=[NSString stringWithFormat:@"fileName=%@",stringImage];

     NSData *dataaa = [concat dataUsingEncoding:NSUTF8StringEncoding];

     [reqqq setHTTPMethod:@"POST"];
     [reqqq setHTTPBody:dataaa];

     NSURLSessionConfiguration *configg=[NSURLSessionConfiguration defaultSessionConfiguration];
     NSURLSession*sessionn=[NSURLSession sessionWithConfiguration:configg delegate:nil delegateQueue:[NSOperationQueue mainQueue]];

    NSURLSessionDataTask *taskk=[sessionn dataTaskWithRequest:reqqq completionHandler:^(NSData *data,NSURLResponse *responce,NSError *error){

    if(error)
    {
        NSLog(@"%@", [error localizedDescription]);
        completionBlock(nil);
    }else{
        NSMutableDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:&error];
        NSLog(@"data %@",d);
        if (d) {
            [arrrrr addObject:d];
        }


        if (completionBlock) {
            completionBlock(arrrrr);
        }
    }
}];
[task  resume];
}

1 个答案:

答案 0 :(得分:0)

    NSString *strRequestUrl = [NSString stringWithFormat:@"%@%@", BASE_URL, apiName];

            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            [manager.requestSerializer setTimeoutInterval:TIMEOUTFORFILETYPEUPLOAD];
            if ([[USERDEFAULTS objectForKey:KEYUSERDETAILS] objectForKey:@"auth_key"]) {
                [manager.requestSerializer setValue:[[USERDEFAULTS objectForKey:KEYUSERDETAILS] objectForKey:@"auth_key"] forHTTPHeaderField:@"authKey"];
                        NSLog(@"AuthKey:%@",[[USERDEFAULTS objectForKey:KEYUSERDETAILS] objectForKey:@"auth_key"]);
            }
            NSData *tempData = nil;

            if ([[NSFileManager defaultManager]fileExistsAtPath:path])
                tempData = [NSData dataWithContentsOfFile:path];

 AFHTTPRequestOperation *operation = [manager POST:strRequestUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
 {                                                 
         if (tempData)
        {
           [formData appendPartWithFileData:tempData name:@"ImageName" fileName:[path  lastPathComponent] mimeType:@"image/png"]; 
        }
    }
  } success:^(AFHTTPRequestOperation *operation, id responseObject)
  {
         NSLog(@"Success: %@", responseObject);
         NSError *error;
         NSDictionary* json = [NSJSONSerialization                                                              JSONObjectWithData:operation.responseData options:kNilOptions error:&error];
         NSLog(@"Responce Data:%@",json);
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) 
 {
        NSLog(@"Error: %@", error.description);
 }];
 [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) 
{
     NSLog(@"Upload Progress %lld",totalBytesWritten*100/totalBytesExpectedToWrite);

}];
[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
                [operation pause];
            }];