This was actually must simpler than I was making it. I just didn't see any examples that put the parameters required in the form into the dictionary. I will lay it out so anyone struggling to see the obvious like myself will have an example to use.
The code below is a direct copy from the link in my question with a few exceptions I'll point out.
NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);//(uploadedImgView.image);
if (imageToUpload)
{
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"My Image Caption", @"caption", userId, @"pid", @"openSesame", @"token", @"users ip address", "ip", nil];
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://myServer"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"/uploadImage" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:@"file" fileName:@"temp.jpeg" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
//NSLog(@"response: %@",jsons);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if([operation.response statusCode] == 403)
{
//NSLog(@"Upload Failed");
return;
}
//NSLog(@"error: %@", [operation error]);
}];
[operation start];
}
The first thing to notice is the NSDictionary *parameters
. This is where you lay out your parameters required in the form. So as you can see from the form in the question I needed a : caption, pid, token, and ip parameter along with all their respective values.
Looking at the form there is one more parameter I didn't mention. Which is this line <input type="file" name="file" size="45"/>
in particular. That portion of the form is handled by this line of code.
[formData appendPartWithFileData: imageToUpload name:@"file" fileName:@"temp.jpeg" mimeType:@"image/jpeg"];
The original question had @"image"
for the name:
value. I fought this for about thirty minutes trying to figure out why I was getting a 500 response from the server when I noticed that my form was expecting @"file"
. Once I changed it everything worked properly.
Just as a note the path:
parameter in multipartFormRequestWithMethod:
is added on to the tail end of the baseURL. So the request will go to @"http://myserver/uploadImage"
as required in the action of the form.
Like I said I hope this spells out the obvious for those like me that tend to overlook it.