带有两个图像文件的Http Post Request

时间:2017-05-19 10:32:28

标签: objective-c

我有问题。我需要将2个jpg文件发送到服务器。我必须使用类似的主体发出POST请求:

身体:     前:图像文件     反向:图像文件

如何使用这两个参数发出此帖子请求?

我尝试使用一个参数:

    static NSString *boundary = @"---------------------------14737809831466499882746641449";
    UIImage *img = [[UIImage alloc] init];
    img = [UIImage imageNamed:@"tarjetaPrueba.jpg"];
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(img, 1.0)];


    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"front\"; \r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:imageData];
    [postbody appendData:[[NSString stringWithFormat:@"--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];

它不起作用......为什么?我不知道......

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您必须将内容类型设置为multipart / form-data。 将两个图像添加到字典中,将其转换为NSData,最后将其附加到请求正文。

contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];

请参阅此链接以获取帮助。

How to send multiple files with post request? (objective-c, iOS)