2012-12-30 105 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 
相关问题