2012-12-30 98 views
-2

我目前正在將JSON數據從我的iOS應用程序發送到我的Web服務器上的PHP腳本。 下面是我使用的iOS系統發送數據的代碼:從iOS發送JSON到PHP服務器上的PHP腳本時上傳文件

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error]; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL: [NSURL URLWithString:@"http://www.myserver.com/upload.php"]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[request setHTTPBody:jsonData]; 

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
[connection start]; 

而在PHP端:

$handle = fopen('php://input','r'); 
$jsonInput = fgets($handle); 
// Decoding JSON into an Array 
$decoded = json_decode($jsonInput,true); 

如何修改兩個iOS的代碼和PHP代碼能夠還要將iOS應用程序中的文件上傳到PHP代碼,然後PHP代碼用它在本地寫入磁盤?該文件將是一個音頻文件。

謝謝!

+0

你檢查http://stackoverflow.com/questions/10711481/sending-file-from-ios-to-php-using -post – Djumaka

+0

是的,但這不是發送JSON數據。 – codeman

+0

您需要使用'x-www-form-urlencoded'編碼發送POST請求,然後在PHP代碼中使用'$ _FILES'變量。 – 2012-12-30 22:33:27

回答

0

我不太瞭解Obj-C,但基本上你需要使用multipart/form-data容器,例如,

Content-Type: multipart/form-data; boundary="xx" 

--xx 
Content-Type: audio/mpeg 
Content-Length: 12345 
Content-Disposition: attachment; name="file"; filename="music.mp3" 

<contents of mp3> 

--xx 
Content-Disposition: form-data; name="data" 
Content-Type: application/json 
Content-Length: 123 

<contents of json data> 

--xx-- 

使用PHP,你可以使用訪問數據:

$_FILES['file'] // the uploaded file 

$_POST['data'] // the json data 
相關問題