将图像从iOS上传到PHP

我一直在努力将UIImage上传到networking服务器。 问题是,图像永远不会出现在服务器上。 一个来自HTML文件的正常POST是有效的。 我认为这是我的Objective-C代码中的一个问题。

这是我的Objective-C代码:

NSData *imageData = UIImagePNGRepresentation(delegate.dataBean.image); NSString *urlString = [NSString stringWithFormat:@"%@test.php", delegate.dataBean.hosterURL]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = [NSString stringWithString:@"---------------------------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=\"uploadedfile\"; filename=\"test.png\"rn"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog([NSString stringWithFormat:@"Image Return String: %@", returnString]); 

这是我的PHP代码:

 <?php $uploaddir = 'uploads/'; $file = basename($_FILES['uploadedfile']['name']); $uploadfile = $uploaddir . $file; echo "file=".$file; //is empty, but shouldn't if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile)) { echo $file; } else { echo "error"; } ?> 

现在我已经自己解决了=)

我忘了身体的反斜杠。

这是正确的身体:

 NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body];