ios通过POST方法上传图片到服务器 [英] Upload image to server through POST method ios

查看:109
本文介绍了ios通过POST方法上传图片到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to upload image to server through post method. The format should be like ["ImageName"=Image]. I have tried the following code but it doesn't upload the image to server. Can anyone help me ?

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

推荐答案

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

这篇关于ios通过POST方法上传图片到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆