我已经准备好从表单接收数据的服务器端 php 代码,我已经对其进行了测试。现在我正在尝试将图像添加到应用程序。这意味着用户不仅会在注册时输入他的姓名和密码以及电子邮件,还会选择要上传的图像。到目前为止我有这个:
Create a urlString with the string data to send.
Prepare an image
Prepare the post string
Create URLRequest and set its parameters
Add a boundary
Prepare Image to Post
Receive Server Response
-(NSDictionary*)addUser:(NSString *)usuario withPass:(NSString *)clave withAddress:(NSString*)direccion withImage:(UIImage*)imagen{
//1.CREATE URL TO SEND
NSString *urlString = [NSString stringWithFormat:@"username=%@&password=%@&email=%@",usuario,clave,direccion];
NSLog(@"user registration string:%@",urlString);
//2.PREPARE IMAGE
NSData *imageData = UIImageJPEGRepresentation(imagen, 90);
//3.POST THE STRING
NSData *postData = [urlString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
//4.CREATE URLREQUEST WITH STRING TO POST TO
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.santiapps.com/learnable/login2/user_add_save.php"]];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
//5.ADD BOUNDARY
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//6.PREPARE IMAGE POST DATA
NSString *name1= [NSString stringWithFormat:@"imagefor%@",usuario];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"images\"; filename=\"%@\"\r\n",name1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//7.PREPARE TO RECEIVE RESPONSE
NSURLResponse *response = nil;
NSError *error = nil;
// Later add code to parse returned data
NSData *myData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSLog(@"server string %@",returnString);
NSError *outError = NULL;
NSDictionary *tempDict = [NSDictionary dictionaryWithJSONData:myData error:&outError];
NSLog(@"Dict of errors:%@",tempDict);
return tempDict;
}