简体   繁体   English

使用POST php iOS上传图像数据

[英]Uploading image data using POST php ios

Here is the code.. 这是代码。

- (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");
}

connection logs Succesffull but im missing something i don't know what 连接日志成功,但我错过了一些我不知道的东西

Here is the php I think the problem may lye here 这是我认为问题可能在于这里的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);

The body data you send should include more information: 您发送的身体数据应包含更多信息:

[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]];

So that the server knows what it received and how to handle it. 这样服务器就知道收到了什么以及如何处理它。 Be sure to create imageData as mutable. 确保将imageData创建为可变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM