我想使用目标c将具有其他参数的图像上传到服务器

时间:2018-06-22 07:46:23

标签: ios objective-c iphone post image-uploading

iOS的新手,遇到了必须将图像上传到服务器的情况。这就是post方法的作用。

- (IBAction)submitClicked:(UIButton *)sender {

    NSDictionary *inputData = [NSDictionary dictionaryWithObjectsAndKeys:myImage,@"coverPic", nil];

NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"http://api.mapartment.in/index.php/events/create"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:70.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];

NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];

NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];

[request setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){


    dispatch_async(dispatch_get_main_queue(), ^{

        NSDictionary *jsondictcity_name = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

        if([[jsondictcity_name valueForKey:@"result"] isEqual:@"true"]){

            NSLog(@"Success");

        }

        else{

            NSLog(@"Try Again");
        }

        [self.view resignFirstResponder];

    });
}

                                      ];
[postDataTask resume];

}

P.S。 _localFilePath包含-/ Users / appcode / Library / Developer / CoreSimulator / Devices / 3C3567B8-03BC-4233-B0BC-97E3899D0AAA / data / Containers / Data / Application / 3D574024-42FB-4305-807A-ACC3C128383F / Documents / png

2 个答案:

答案 0 :(得分:1)

图像不会与其他参数一起传递,您必须将图像转换为NSData

   UIImage *yourImage= [UIImage imageNamed:@"image.png"];
   NSData *imageData = UIImagePNGRepresentation(yourImage);
   NSString *postLength = [NSString stringWithFormat:@"%d", [imageData length]];

然后在请求中传递这些数据

 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
 [request setHTTPBody:imageData];

和其他参数作为json传递。

使用路径获取UIImage

 UIImage *yourImage = [UIImage imageWithContentsOfFile: imageFilePath]; 

答案 1 :(得分:0)

- (IBAction)submitClicked:(UIButton *)sender {
    UIImage* image = [UIImage imageWithContentsOfFile:_localFilePath];
    NSString *myImage = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSDictionary *inputData = [NSDictionary dictionaryWithObjectsAndKeys:myImage,@"coverPic",@"POEM WRITING",@"title",@"Bring your own paper",@"desc", nil];

    NSError *error;
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"http://api.mapartment.in/index.php/events/create"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
    cachePolicy:NSURLRequestUseProtocolCachePolicy
    timeoutInterval:70.0];

    [request addValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPMethod:@"POST"];

    NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];

    [request setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){


    dispatch_async(dispatch_get_main_queue(), ^{

    NSDictionary *jsondictcity_name = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

    if([[jsondictcity_name valueForKey:@"result"] isEqual:@"true"]){

    NSLog(@"Success");

    }

    else{

    NSLog(@"Try Again");
    }

    [self.view resignFirstResponder];

    });
    }

    ];
    [postDataTask resume];

    }