我有一个简单的问题 - 我目前正在写一个特定的部分在我的应用程序有关发送数据到服务器。发送UIImage和文本到服务器
我试着发送文本,成功了。发送图像,成功。 我现在想要做的是在一个POST请求中发送它们。 我发现我需要使用称为multipart/form-data和边界的东西,但我还没有找到有关它的信息。
那么如何在一个简单的POST请求中发送文本和图像呢?我怎样才能检查上传过程中的错误,事后等?
谢谢!
参考代码,我已经写了,但发送0字节的信息的:
NSData *imageData = UIImageJPEGRepresentation(sendImage, 1.0);
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://posttestserver.com/post.php?dir=something"]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------54737809831466490885746641449";
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:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"reportingImage.jpg\"rn" 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]];
[body appendData:[@"Content-Type: text/xml" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[[alertView textFieldAtIndex:0] text] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
几个PARAMS试试这个http://stackoverflow.com/questions/14598044/how-to-send-image-and-text-toget她使用nsmutableurlrequest – Buntylm
在该答案的代码工作,非常感谢! –
我也给出了同样的答案。 – Buntylm