我是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"这样的图像路径吗

最佳答案

一种可能的解决方案是:

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];

希望有帮助

关于ios - 使用NSURL发布图像文件和字符串文本参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33411227/

10-11 22:27
查看更多