我正在尝试上传图片和一些文字。我能够发布文本,但不知何故图像无法到达服务器。
以下是我的代码:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *password = [[Utilities sharedConfiguration] sha1:txtPassword.text];
NSString *post = [NSString stringWithFormat:@"id_sender=%@&token=%@&array_receiver=%@&message=%@&time_allowed=%@&password=%@",[defaults objectForKey:@"id_user"],[defaults objectForKey:@"token"],selectedContact,txtMessage.text,txtTime.text,password];
NSLog(@"post %@",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableData *data = [NSMutableData dataWithData:postData];
//NSMutableData *data = nil;
if(myimage!=nil){
NSString *boundary = @"---------------------------14737809831466499882746641449";
[data appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filetype=\"image/png\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[NSData dataWithData:UIImagePNGRepresentation(myimage)]];
}
NSString *postLength = [NSString stringWithFormat:@"%d", [data length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://www.myurl.com/send_message_17294.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:data];
[MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
[NSURLConnection connectionWithRequest:request delegate:self];