NSURLSessionUploadTask does not transfer file to PHP script

EDIT: Well, I just set the content type header to multipart / form-data no difference. My initial question is below:


This is my first stack overflow question, I hope everything is correct.

I only study Objective-C, having recently completed the online version of the Stanford course. I don't know anything about php and html. The PHP script and html that I use are mostly copied from the tutorial. Obj-C makes more sense to me.

Problem:

I have a php script. It loads an image file. It works correctly when called from an html file in the same folder on the server. I am trying to get the same script to work when it is called from my obj-c. It seems to start, it returns 200, obj-c does call php, but there is no file in the online folder.

The Internet seems to have very little about this since it was introduced only in ios7. No examples that I have found relate to file downloads, they all deal with downloading and just say that the download is similar. What I did seems to suit any tutorials I found.

I know:

  • php works and the file is loaded when it is called from the html file on the server
  • obj-c definitely calls a php script (I wrote several protocols (using file_put_contents) in php that confirm that a script is called when obj-c is started
  • obj-c almost certainly loads the image file (if I use the delegate method in obj-c, it shows the loading progress)
  • but the php script does not receive the file (the log I wrote in php shows that $ _FILES doesn't matter when called from obj-c. When called from html it works as expected)
  • php , , Content-Length .

:

  • html, , , , ( NSURLSessionUploadTask), , NSURLSessionUploadTask ? ?
  • [ ] 200, quote: {URL: (URL- PHP )} { : 200, { Connection = "Keep-Alive"; "Content-Type" = "text/html"; Date = "Thu, 16 Jan 2014 19:58:10 GMT"; "Keep-Alive" = "timeout = 5, max = 100"; Server = Apache; "Transfer-Encoding" = Identity; }}
  • html enctype = "multipart/form-data", , obj-c -?
  • .
  • ! :)
  • edit, , [request setHTTPMethod: @ "POST" ] [request setHTTPMethod: @ "PUSH" ], , .

C

- (void) uploadFile: (NSURL*) localURL toRemoteURL: (NSURL*) phpScriptURL
{
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:phpScriptURL];
    [request setHTTPMethod:@"POST"];
    NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:localURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        if (error == nil)
        {
            NSLog(@"NSURLresponse =%@",  [response description]);
            // do something !!!
        } else
        {
            //handle error
        }
        [defaultSession invalidateAndCancel];
    }];

    self.imageView.image = [UIImage imageWithContentsOfFile:localURL.path]; //to confirm localURL is correct

    [uploadTask resume];
}

PHP script,

<?php

        $file = 'log.txt';
        $current = file_get_contents($file);
        $current .= $_FILES["file"]["name"]." is being uploaded. ";  //should write the name of the file to log.txt 
        file_put_contents($file, $current);


    ini_set('display_errors',1);
    error_reporting(E_ALL);

   $allowedExts = array("gif", "jpeg", "jpg", "png");
   $temp = explode(".", $_FILES["file"]["name"]);
   $extension = end($temp);   

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    //&& ($_FILES["file"]["size"] < 100000) //commented out for error checking
    && in_array($extension, $allowedExts))
      {
      if ($_FILES["file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        }
      else
        {
            echo "Upload: " . $_FILES["file"]["name"] . "<br>";
            echo "Type: " . $_FILES["file"]["type"] . "<br>";
            echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
            echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

            if (file_exists("upload/" . $_FILES["file"]["name"]))
              {
              echo $_FILES["file"]["name"] . " already exists. ";
              }
            else
              {
              if (move_uploaded_file($_FILES["file"]["tmp_name"],
              "upload/" . $_FILES["file"]["name"]))
              {
                echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
              }
              else
              {
                echo "Error saving to: " . "upload/" . $_FILES["file"]["name"];
              }

            }
        }
      }
    else
      {
      echo "Invalid file";
      }

?>

, html , script

<html>
<body>

    <form action="ios_upload.php" method="post"
    enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file"><br>
    <input type="submit" name="submit" value="Submit">
    </form>

</body>

+4
1

: fooobar.com/questions/1522256/...

, .

PHP, .

:

Objective-C :

- (void) uploadFile: (NSURL*) localURL toRemoteURL: (NSURL*) phpScriptURL
{
    // Create the Request
     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:phpScriptURL];
    [request setHTTPMethod:@"POST"];

    // Configure the NSURL Session
     NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.upload"];
    [sessionConfig setHTTPMaximumConnectionsPerHost: 1];

     NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:nil];

     NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:localURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
         if (error == nil)
         {
              NSLog(@"NSURLresponse =%@",  [response description]);
              // do something !!!
         } else
         {
             //handle error
         }
         [defaultSession invalidateAndCancel];
     }];

      self.imageView.image = [UIImage imageWithContentsOfFile:localURL.path]; //to confirm localURL is correct

     [uploadTask resume];
}

PHP:

<?php
    // Get the Request body
    $request_body = @file_get_contents('php://input');

    // Get some information on the file
    $file_info = new finfo(FILEINFO_MIME);

    // Extract the mime type
    $mime_type = $file_info->buffer($request_body);

    // Logic to deal with the type returned
    switch($mime_type) 
    {
        case "image/gif; charset=binary":
            // Create filepath
             $file = "upload/image.gif";

            // Write the request body to file
            file_put_contents($file, $request_body);

            break;

        case "image/png; charset=binary":
            // Create filepath
             $file = "upload/image.png";

            // Write the request body to file
            file_put_contents($file, $request_body);

            break;

        default:
            // Handle wrong file type here
            echo $mime_type;
    }
?>

: https://github.com/gingofthesouth/Audio-Recording-Playback-and-Upload

iOS, .

, .

0

All Articles