1

我有一個使用NSURLSessionUploadTask的iOS應用程序中的視頻上傳系統。視頻文件被保存到一個NSURL,所以我用我上傳方法如下代碼:使用NSURLSessionUploadTask將文件上傳到PHP服務器

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

我有(使用Laravel)下運行Nginx的處理這種上傳一個PHP服務器。我用郵遞員測試了它,並且它接受上傳正常(期待名爲「文件」的文件)。

當我運行上面的objc代碼時,服務器告訴我沒有文件上傳($_FILES數組爲空)。

我試過了,沒有設置「fileName」標題,我試過將「Content-Type」設置爲「multipart/form-data」,但沒有一個可以工作。

我怎樣才能得到NSURLSessionUploadTask正確上傳這些文件(從NSURL)到服務器?

此信息似乎細節類似的問題:NSURLSessionUploadTask not passing file to php script

+0

你的檔案裏有什麼?請記住,PHP將期待身體看起來像[基於表單的文件上傳](http://stackoverflow.com/questions/8659808/how-does-http-file-upload-work),並uploadTaskWithRequest doesn我不會做任何「聰明」的事 - 我只是把你的文件作爲身體數據發送出去。 – 2014-10-01 08:20:49

+0

這是一個.mov文件。 – GTF 2014-10-01 10:21:07

+0

只需使用AFNetworking並通過手動編寫auth頭文件(base64編碼等)來解決身份驗證問題就解決了這一問題。 – GTF 2014-10-02 11:08:08

回答

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

我希望有幫助。

+0

我使用AFNetworking找到了一個方法,所以不能測試這個,但會記住它的未來裁判,謝謝。 – GTF 2015-02-02 09:01:59

+0

我們可以發佈參數嗎?因爲我想發佈但沒有找到成功 – Mukesh 2015-06-30 07:05:15

相關問題