-2

I'm currently sending JSON data from my iOS app to a PHP script on my web server. Here's the code I'm using in iOS to send the data:

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

And on the PHP side:

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

How can I modify both the iOS code and the PHP code to be able to also upload a file from the iOS app to the PHP code, that the PHP code then uses to write to disk locally? The file would be an audio file.

Thanks!

codeman
  • 8,868
  • 13
  • 50
  • 79

1 Answers1

0

I don't know much about Obj-C, but basically you need to use the multipart/form-data container, e.g.

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

With PHP you can access the data using:

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

$_POST['data'] // the json data
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309