Skip to content Skip to sidebar Skip to footer

Nsurlsessionuploadtask Not Passing File To Php Script

EDIT: Ok, I just set the content-type header to multipart/form-data with no difference. My original question is below: This is my first question on stack overflow, I hope I'm doi

Solution 1:

I just answered this same question over here: https://stackoverflow.com/a/28269901/4518324

Basically, the file is uploaded to the server in the request body as binary.

To save that file in PHP you can simply get the request body and save it to file.

Your code should look something like this:

Objective-C Code:

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

    // Configure the NSURL SessionNSURLSessionConfiguration *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 Code:

<?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 returnedswitch($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 hereecho$mime_type;
    }
?>

I wrote a code example of recording audio and uploading it to a server here: https://github.com/gingofthesouth/Audio-Recording-Playback-and-Upload

It shows code from saving on the iOS device, to uploading and saving to the server.

I hope that helps.

Post a Comment for "Nsurlsessionuploadtask Not Passing File To Php Script"