简体   繁体   中英

Uploading images to server PHP script from iPhone app

I am trying to upload two images to server using the below code

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);
                               }
                           }];

But I always get failed to upload.

This is php script used on server.

<?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!"));

?>

You call [urlrequest setHTTPBody:...] 3 times, each call invalidating the previous one. Maybe try to concatenate your data, calling setHTTPBody only once...

Also, you're making a Synchronous call +[NSUrlConnection sendSynchronousRequest:returningResponse:error:] (with no NSURLResponse ** parameter - which might give you some insight about what happened), and an asynchronous one ( sendAsynchronousRequest:queue:completionHandler: ) just after

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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