将附加的帖子数据与jpeg一起添加到NSURLConnection

时间:2013-11-16 12:44:12

标签: php ios7 uiimage nsurlconnection

使用NSURLConnection时,我无法上传文件和其他简单的帖子信息。我知道关于这个问题已经有很多问题,但它们似乎都没有回答我的问题,所以如果有人回答我会提前道歉,如果你能指出我正确的方向,那就太好了。

我正在使用此代码上传jpeg选择的相机胶卷:

    NSData *imageData = UIImageJPEGRepresentation(image, 50);

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    [request setTimeoutInterval:10];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename='profileImage.jpg'rn",usernameString] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-streamrnrn" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // setting the body of the post to the reqeust
    [request setHTTPBody:body];

    // now lets make the connection to the web
    registerConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    [registerConnection start];

但是我还需要再发送2个值作为帖子信息,例如funcID = 1和username = sampleUsername,这样我的php代码就知道该如何处理该文件。我试图将appendData附加到当前正文,例如:

[body appendData:[[NSString stringWithFormat:@"funcCode=1&username=%@",
                     usernameString] dataUsingEncoding:NSUTF8StringEncoding]]; 

但它不起作用,我不确定为什么。

非常感谢任何帮助,谢谢!

0 个答案:

没有答案