使用POST php ios上传图像数据

时间:2014-04-22 18:03:11

标签: php ios

这是代码..

- (IBAction)buttonClicked:(id)sender {   
    UIImage *yourImage= [UIImage imageNamed:@"img.png"];
    NSData *imageData = UIImagePNGRepresentation(yourImage);
    NSString * postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[imageData length]];
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://address/foldername/upload.php?"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:imageData];
    NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];   
    if (conn) NSLog(@"Connection Successful");
}

连接日志成功但我错过了一些我不知道的内容

这是php 我认为这个问题可能就在这里。

//This is the directory where images will be saved 
$con = mysql_connect("localhost" ,"root" , "");
if(!$con){
    die('Could not connect' . mysql_error());
}
mysql_select_db("Databasename",$con);

//upload your file
$uploaddir = './Uploads/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "/uploads/{$file}";
}
mysql_close($con);

1 个答案:

答案 0 :(得分:1)

您发送的正文数据应包含更多信息:

[imageData appendData:[@"Content-Disposition: form-data; name=\"image\"; filename=\"name.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[imageData appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

以便服务器知道它收到了什么以及如何处理它。务必将imageData创建为可变的。