1

我在 iOS 应用程序中有一个视频上传系统,使用NSURLSessionUploadTask. 视频文件保存到一个NSURL所以我在我的上传方法中使用以下代码:

request.HTTPMethod = @"POST";
[request addValue:@"file" forHTTPHeaderField:@"fileName"];

// Create upload task
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:filePath completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if(!error) {
        // handle success
    } else {
        // handle error
    }
}];

// Run the task
[task resume];

我有一个在 nginx 下运行的 PHP 服务器(使用 Laravel)来处理这个上传。我已经用 Postman 对其进行了测试,它可以很好地接受上传(期望一个名为“file”的文件)。

当我运行上面的 objc 代码时,服务器告诉我没有上传文件($_FILES数组为空)。

我尝试过设置和不设置“fileName”标头,并且尝试将“Content-Type”设置为“multipart/form-data”,但这些都不起作用。

如何才能NSURLSessionUploadTask将这些文件(从NSURL)正确上传到服务器?

这篇文章似乎详细介绍了一个类似的问题:NSURLSessionUploadTask not pass file to php script

4

1 回答 1

8

当使用 NSURLSessionUploadTask [uploadTaskWithRequest: fromFile:] 时,文件以二进制形式在请求正文中发送。

要在 PHP 中保存该文件,您可以简单地获取请求正文并将其保存到文件中。

显然,最好进行某种文件格式验证。

Objective-C 代码:

// 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代码:

<?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
    }
?>

我在这里写了一个录制音频并将其上传到服务器的代码示例: https ://github.com/gingofthesouth/Audio-Recording-Playback-and-Upload

我希望这会有所帮助。

于 2015-02-02T01:19:48.273 回答