Uploading file using NSURLSessionUploadTask to PHP server

大憨熊 提交于 2019-12-01 13:17:17

When using NSURLSessionUploadTask [uploadTaskWithRequest: fromFile:], the file is sent in the request body as binary.

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

Obviously, it is best to do some sort of file format validation.

Objective-C Code:

// Define the Paths
NSURL *URL = [NSURL URLWithString:kDestinationURL];

// Create the Request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

// Configure the NSURL Session
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.upload"];
config.HTTPMaximumConnectionsPerHost = 1;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

// Define the Upload task
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:audioRecorder.url];

// Run it!
[uploadTask resume];

PHP Code:

<?php
    // File Path to save file
    $file = 'uploads/recording.m4v';

    // 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 "video/mp4; charset=binary":

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

            break;

        default:
            // Handle wrong file type here
    }
?>

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

I hope that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!