I personally using this method to communicate and upload staff to server this is a json type of approach:
- (NSURLRequest *)convertToRequest:(NSString *)stringURL withDictionary:(NSDictionary *)dictionary
{
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSURL *url = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: JSONData];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept-Encoding"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[JSONData length]] forHTTPHeaderField:@"Content-Length"];
return request;
}
The dictionary parameter is filled with something like:
first convert the data to base64String something like:
NSData *data = UIImageJPEGRepresentation(self.userImageView.image, 1.0);
NSData *imageBase64Data = [data base64EncodedDataWithOptions:0];
NSString *imageBase64String = [[NSString alloc] initWithData:imageBase64Data encoding: NSUTF8StringEncoding];
add this to dictionary...
NSDictionary *jsonDictionary = @{
@0 : @{
"name": "file1",
"image" : imageBase64String1
},
@1 : @{
"name": "file2",
"image" : imageBase64String2
} //and so on..
};
//you may want to put that in a loop
[ImplementationClass convertToRequest:YourServerURL withDictionary: jsonDictionary];
and at the server side something like:
decodes the data sent to server (PHP):
// Retrieves data
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$json_decoded = json_decode($jsonInput,true);
/*
* I commented this because i'm not sure if this suits my `NSDictionary` above
* but you can always check by logging `$json_decoded` or probably `var_dump()` function of php
*
* $json_decoded[0]['name'];
* $json_decoded[0]['image'];
* $json_decoded[1]['name'];
* $json_decoded[1]['image'];
*/
function upload_image($filename, $uploadedfile) {
$save_file_path = getcwd()."/uploads/";
$save_file_path .= $filename;
$image_file = base64_decode($uploadedfile);
//DELETES EXISTING
if (file_exists($save_file_path)) { unlink($save_file_path); }
//CREATE NEW FILE
file_put_contents($save_file_path, $image_file);
//CHECK FILE IF EXIST
return ((file_exists($save_file_path)) ? true : false );
}
hope this is helpful for you.. cheers..
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…