I am currently working on gallery kind of iPhone application. According to my requirement, i need to store all the camera captured image into document directory. there is so
Here is my sample code
NSURL *nsurl =[NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setURL:nsurl];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
//Image
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n",[fileName text]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
You need to use/ call the API in a recursive function to get this done.
Serverside Code
//Create a folder named images in your server where you want to upload the image.
// And Create a PHP file and use below code .
<?php
$uploaddir = 'images/';
$ran = rand () ;
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir .$ran.$file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "www.host.com/.../images/{$uploadfile}";
}
?>
Application Side code
- (IBAction)uploadClicked:(id)sender
{
[self UploadTheImageNow:0];
}
The below code is for the recursive function which will continue till all the image upload will get finish.
-(void)UploadTheImageNow:(NSInteger)count
{
// UIImage *updatedImage=[UIImage ImageNamed:@" Your Image name / you can get from array"];
UIImage *updatedImage=[UIImage ImageNamed:[yourArray ObjectAtIndex:ic]];
NSData *imageData = UIImageJPEGRepresentation(updatedImage, 90);
NSString *urlString = @"your URL link";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name="userfile"; filename="ipodfile.jpg"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([(NSHTTPURLResponse *)response statusCode]==200)
{
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"Finished with jsonObject %@", jsonObject);
count++;
if(count<20)
{
[self UploadTheImageNow:count];
}
else
{
// Finished Uploading all Images
}
}
}];
}
You can do it with afnetwroking
-(void)saveServerData:(UIImage *)image{
NSData *imageToUpload = UIImageJPEGRepresentation(image, 1.0);
if (imageToUpload)
{
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
GameId, @"gameid"
, useremail, @"userid"
, PartIndex, @"imageposition"
, nil];
NSString *url=[NSString stringWithFormat:@"%@addplayerresponse",BASE_URL];
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:url]];
NSLog(@"%@",parameters);
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:url parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:@"image" fileName:[NSString stringWithFormat:@"%@_%@.jpeg",appDelegate.userid,appDelegate.onlineGameId] 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:%@",parameters);
//success
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if([operation.response statusCode] == 403)
{
return;
}
NSLog(@"error: %@", [operation error]);
}];
[operation start];
}
}
And i don't think you can upload folder either you have to upload one image at a time or you have to make zip the folder and send it, and in the php you have to unzip it after saving it.
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:pathToStoreImage]);
NSString *str = [self base64StringFromData:imageData length:0];
And then you can pass the str object to any parameter of server.
use the base64StringFromData function in your .m file;
-(NSString *) base64StringFromData: (NSData *)data length: (int)length {
unsigned long ixtext, lentext;
long ctremaining;
unsigned char input[3], output[4];
short i, charsonline = 0, ctcopy;
const unsigned char *raw;
NSMutableString *result;
lentext = [data length];
if (lentext < 1)
return @"";
result = [NSMutableString stringWithCapacity: lentext];
raw = [data bytes];
ixtext = 0;
while (true) {
ctremaining = lentext - ixtext;
if (ctremaining <= 0)
break;
for (i = 0; i < 3; i++) {
unsigned long ix = ixtext + i;
if (ix < lentext)
input[i] = raw[ix];
else
input[i] = 0;
}
output[0] = (input[0] & 0xFC) >> 2;
output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
output[3] = input[2] & 0x3F;
ctcopy = 4;
switch (ctremaining) {
case 1:
ctcopy = 2;
break;
case 2:
ctcopy = 3;
break;
}
for (i = 0; i < ctcopy; i++)
[result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];
for (i = ctcopy; i < 4; i++)
[result appendString: @"="];
ixtext += 3;
charsonline += 4;
if ((length > 0) && (charsonline >= length))
charsonline = 0;
}
return result;
}