我目前正在使用Objective C在Xcode中构建应用程序,我需要发布两个文本变量和一个图像。目前,我只能发布两个文本变量,但我想通过HTTP POST请求中的FILES变量将我的UIImageView中的图像发送到服务器。
以下是我的POST请求的工作代码:
- (IBAction)posttoserver:(id)sender {
NSString *post = [NSString stringWithFormat:@"process=writepost&auth_token=%@&app_id=0&posttextarea=%@&url=%@", authkey, encodedmessage, encodedlink];
NSData *data = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength = [NSString stringWithFormat:@"%lu", (unsigned long)[data length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"my-server.com"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postlength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:data];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(@"Connection!");
}
else {
NSLog(@"No Connection");
}
[_posttext resignFirstResponder];
[_postlink resignFirstResponder];
}
(续):
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Post Response: %@", response);
if ([response isEqualToString:@"success"]) {
// NSLog Success
}
else {
// Something is wrong
}
}
如您所见,我发布了用户可编辑文本以及帖子的链接。此外,您可能会注意到我附加了“process = writepost& auth_token =%@& app_id = 0”,服务器只需要识别谁正在发布以及将哪些进程发送到特定URL。
现在,我想通过添加UIImageView中的图像将图像附加到POST请求。如何将它附加到POST请求的FILES变量中?
任何帮助都会很高兴。
提前致谢, 凯尔