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

5
  • Have you checked stackoverflow.com/questions/10711481/… Commented Dec 30, 2012 at 22:08
  • Yes, but that's not with sending JSON data. Commented Dec 30, 2012 at 22:13
  • You'll want to send a POST request using the x-www-form-urlencoded encoding, then use the $_FILES variable in the PHP code. Commented Dec 30, 2012 at 22:33
  • @H2CO3 You mean multipart/form-data I hope? Commented Dec 31, 2012 at 1:39
  • @Jack Oh, yes. Sorry, it was 1AM here. Commented Dec 31, 2012 at 6:43

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.