Upload image to server through POST method ios

廉价感情. 提交于 2019-12-11 12:22:51

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/37590959/upload-image-to-server-through-post-method-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!