从iPhone应用程序上传图像到服务器PHP脚本


Uploading images to server PHP script from iPhone app

我正在尝试使用以下代码将两个图像上传到服务器

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    question = [defaults objectForKey:@"question"];
    userID = [defaults objectForKey:@"userID"];
    userName = [defaults objectForKey:@"firstName"];
    lastName = [defaults objectForKey:@"lastname"];
    NSData *thisImage = [defaults dataForKey:@"thisImage"];
    NSData *thatImage = [defaults dataForKey:@"thatImage"];
    NSString *numbVotes = [defaults objectForKey:@"votes"];
    NSURL *aUrl = [NSURL URLWithString:@"http://myurl/url.php"];
    NSMutableURLRequest *urlrequest = [NSMutableURLRequest requestWithURL:aUrl
                                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                          timeoutInterval:60.0];
    [urlrequest setHTTPMethod:@"POST"];
    NSString *postString = [NSString stringWithFormat: @"user_id=%@&user=%@&question=%@&required_votes=%@", userID, userName, question, numbVotes];
    connection = [[NSURLConnection alloc] initWithRequest:urlrequest delegate:self startImmediately:NO];
    [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [connection start];
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [urlrequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
    // now lets create the body of the post
    NSMutableData *image1 = [NSMutableData dataWithData:thisImage];
    [image1 appendData:[[NSString stringWithFormat:@"'r'n--%@'r'n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
  //  [image1 appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name='"userfile'"; filename='"ipodfile.jpg'"'r'n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [image1 appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream'r'n'r'n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [image1 appendData:[NSData dataWithData:thisImage]];
    [image1 appendData:[[NSString stringWithFormat:@"'r'n--%@--'r'n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    NSMutableData *image2 = [NSMutableData dataWithData:thatImage];
    [image2 appendData:[[NSString stringWithFormat:@"'r'n--%@'r'n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
   // [image2 appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name='"userfile'"; filename='"ipodfile.jpg'"'r'n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [image2 appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream'r'n'r'n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [image2 appendData:[NSData dataWithData:thisImage]];
    [image2 appendData:[[NSString stringWithFormat:@"'r'n--%@--'r'n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    // setting the body of the post to the reqeust
    [urlrequest setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    [urlrequest setHTTPBody:image1];
    [urlrequest setHTTPBody:image2];
    // now lets make the connection to the web
    NSData *returnData = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",returnString);

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:urlrequest queue:queue 
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ([data length] >0 &&
                                   error == nil){
                                   html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   dataRec = [[NSMutableData alloc] initWithData:data];
                                   NSString *string = [[NSString alloc] initWithData:dataRec encoding:NSUTF8StringEncoding];
                                   NSLog(@"HTML = %@", string);
                               }
                               else if ([data length] == 0 && error == nil){
                                   NSLog(@"Nothing was downloaded here.");
                               }
                               else if (error != nil){
                                   NSLog(@"Error happened here = %@", error);
                               }
                           }];

但我总是上传失败。

这是服务器上使用的php脚本。

<?php
include_once('clsData.php');
$oData = new clsData();
$dbconn = $oData->dbconn;
$user_id= trim($_POST["user_id"]);
$user_names = trim($_POST['user']);
$question= trim($_POST["question"]);
$required_votes= trim($_POST["required_votes"]);
$success=0;
$error=0;
$ctime= $user_id . "_" . (microtime(true)*10000);
/////////////// for this image
$target_dir = "uploads/";
 $target_path_this = $target_dir . $ctime."_this.jpg"; 
if(move_uploaded_file($_FILES['image_this']['tmp_name'], $target_path_this)) {
   $success++;
} else{
    echo json_encode(array ('value'=>"error",'label'=>"Failed to upload This file!"));
    return;
}

/////////////////////////////for that image
$target_path = "uploads/";
  $target_path = $target_path . $ctime."_that.jpg"; //basename( $_FILES['image_that']['name']); 

if(move_uploaded_file($_FILES['image_that']['tmp_name'], $target_path)) {
      $success++;
} else{
    echo json_encode(array ('value'=>"error",'label'=>"Failed to upload That file!"));
   return;
}

$sql = "
    INSERT INTO `thisthat_questions` (
        user_id,
        user,
        required_votes,
        question,
        image_this,
        image_that
    ) VALUES (
        " . $user_id . ",
        '" . $user_names . "',
        " . $required_votes . ",
        '" . $question . "',
        '" . $ctime."_this.jpg" . "',
        '" . $ctime."_that.jpg" . "'
    )"; 

if($result = mysql_query($sql,$dbconn))
{
     $success++;
} 
else 
{
    echo json_encode(array ('value'=>"error",'label'=>"Database inser failed!"));
   return;
} 
 echo json_encode(array ('value'=>"success",'label'=>"Asked Question!"));
?>

您调用[urlrequest setHTTPBody:...] 3次,每次调用都会使上一次调用无效。也许尝试连接您的数据,只调用setHTTPBody一次。。。

此外,您正在进行一个同步调用+[NSUrlConnection sendSynchronousRequest:returningResponse:error:](没有NSURLResponse **参数,这可能会让您了解发生了什么),并在之后进行一个异步调用(sendAsynchronousRequest:queue:completionHandler: