我是iOS新手。我试图使用POST方法发布一些数据,包括图像文件。 picture
是最后一个参数
NSString *post = [[NSString alloc]initWithFormat:@"first_name=%@&last_name=%@&email=%@password=%@&picture",[_firstName text],[[_lastName text],[_email text],[_password text],[What to Add Here]];
NSLog(@"%@",post);
NSURL *url = [NSURL URLWithString:@"http://test.test.com/ws/customer/authenticate"];
//Additional info
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
//[request setValue:postLength forKey:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Response code: %ld", (long)[response statusCode]);
我可以使用像@"demo.jpg"
答案 0 :(得分:1)
可能的解决方案之一是:
UIImage *image = [UIImage imageNamed: "demo.png"];
NSData *dataImage = UIImagePNGRepresentation(image);
// request
...
[request setHTTPBody: dataImage];
在您的情况下,您可以使用base64:
UIImage *image = [UIImage imageNamed: "demo.png"];
NSData *dataImage = UIImagePNGRepresentation(image);
NSString *stringImage = [dataImage base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSString *post = [[NSString alloc]initWithFormat:@"first_name=%@&last_name=%@&email=%@password=%@&picture",[_firstName text],[[_lastName text],[_email text],[_password text], stringImage];
希望有所帮助
答案 1 :(得分:0)
你应该将图像数据转换为字符串格式并用作参数,如果你直接使用这个字符串值,我们就无法正确地检索图像。所以用图像字符串中的'+'字符替换任何值(比如@“sdfs4546dgdggdterteradv”)。然后后端应该将此值替换为“+”并存储。