使用图像发送http post请求时出错

时间:2012-05-29 16:14:54

标签: iphone ios xcode http post

我从几天开始就遇到了这个问题,我真的需要你的帮助。

我实际上是想通过php脚本将我的iphone应用程序中的文件上传到网络服务器。

这是我在Xcode中的方法:

-(void)sendPost{
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"back.png"];

    NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
    NSString *urlString = @"myscriptishere.php";
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    [request setTimeoutInterval:60.0];
    [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:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\";filename=\"myfile.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];
    NSLog(@"%@",[[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding]);
    // Do any additional setup after loading the view.

}

我的php代码是:

<?php
    $domainpath = $_SERVER['DOCUMENT_ROOT'];
    $target = "./upload";
    $public = "/public/upload/";
    $target = $target.basename( $_FILES['userfile']['name']) ;
    $check = getimagesize($_FILES['userfile']['tmp_name']);

    if (move_uploaded_file($_FILES["file"]["tmp_name"],
                           $domainpath. $public . $_FILES["file"]["name"]))
    echo "YES";

    else
    echo "NO";


    ?>

我总是收到(几秒钟之后,所以我猜我上传的东西)服务器回复“否”。

我已经检查过我有权写我要写的文件夹。

关于问题可能隐藏在哪里的任何想法?

提前完成

1 个答案:

答案 0 :(得分:0)

你的问题在这里:

NSString *urlString = @"myscriptishere.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setTimeoutInterval:60.0];
[request setURL:[NSURL URLWithString:urlString]];

您要发布到文件名。您的urlString变量应包含完整地址,包括协议和域(如@"http://localhost/myscriptishere.php")。