I have been looking everywhere online for a way to upload an image from an iOS app via PHP using AFNetworking 2.0 to a mySQL database. I have finally found a solution after searching and searching. I can take a picture and upload it to my database. When I download the image it saves as "Locations-29.image" or "Locations-30.image" I just don't get why the file extension is .image? When the image saves to the database it shows up like this: /var/lib/php/session/phpA7fFDB
I would really appreciate any help. Is it something to do with the Xcode? My question really is how can I save it as a .jpeg/png file rather than what I'm getting now? and is it okay for the URL to be /var/lib/php/session/phpA7fFDB ?
Here is my code:
- (IBAction)postImageToServer:(UIButton*)sender {
CGFloat compression = 1.0f;
UIImage *image = _uploadImage.image;
NSData *imageData1 = UIImageJPEGRepresentation(image, compression);
int random = arc4random() % 9999999;
NSString *photoName=[NSString stringWithFormat:@"%d-image.jpg",random];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://urlhere.com"]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = @{@"fileName": photoName};
AFHTTPRequestOperation *op = [manager POST:@"getImage.php?" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData1 name:@".jpg" fileName:photoName mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
[op start];
}
This is my PHP file:
<?php
$hostusername = "";
$hostpassword = "";
$hostname = "";
$name = $_POST['name'];
$image1 = basename($_FILES['image']['tmp_name']);
$tmp_img = $_FILES['image']['tmp_name'];
$dbhandle = mysql_connect($hostname, $hostusername, $hostpassword)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("em",$dbhandle)
or die("Could not select userName");
$query = mysql_query("INSERT INTO Locations (name, image)
VALUES ('$name','$tmp_img')");
mysql_close($dbhandle);
?>