0

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 some 10-20 image files in document folder and after that i have to push that application resource document folder on server using single php url. I have attached screenshot for displaying resource folder with some image files.

enter image description here

here is my PHP Code :

  $file_path = "../Gallery/";

   $file_path = $file_path . basename( $_FILES['Documents']['name']);
   if(move_uploaded_file($_FILES['Documents']['tmp_name'], $file_path)) {
       echo "Image is upload";
   } else{
       echo "Image is not Upload";
   }

Can someone help me how can i upload document folder on php server ?

Thanks in advance.

Anand Gautam
  • 2,541
  • 3
  • 34
  • 70

4 Answers4

0
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;
}
Raviraj Jadeja
  • 849
  • 6
  • 17
  • @RavirajThanks for your suggestion but i didnt get it properly, can you pls explain ur above code? my php url is... abc.123.com.sg/...../Mobile/Api/gallery_api.php – Anand Gautam Dec 11 '13 at 07:41
  • OK fine you might have path of the image stored in the iOS app. Fetch the path and convert the image to nsdata, further convert the data to string. Now in your backend service create a parameter which accepts a string. Create a POST method in backend and then pass the image string as parameter – Raviraj Jadeja Dec 11 '13 at 07:43
  • but number of images is not fixed.. it can be more than fifty. Thats why i have converted all image in UUID string value. Is it necessary to send data only for images on server and what is base64EncodingTable ? – Anand Gautam Dec 11 '13 at 07:46
  • Okay @Raviraj..can you attach some code idea for posting image data on server using php url. – Anand Gautam Dec 11 '13 at 07:51
  • we are using two files created by us and thats like a big code for synching. You can search some tutorials helpful to you but the only thing you need to know is this is how the image and video are synchronised. Whenever you have the code for posting pass the string as a parameter for the UIimage object – Raviraj Jadeja Dec 11 '13 at 07:54
  • Is it possible by using AFNetworking framework. see this link - http://stackoverflow.com/questions/17294579/upload-image-to-php-web-server-from-ios?rq=1 http://stackoverflow.com/questions/13679009/how-to-post-an-image-to-the-web-server – Anand Gautam Dec 11 '13 at 07:59
  • haven't tried it but yet it would be possible, there is not cost we have to pay in trying it – Raviraj Jadeja Dec 11 '13 at 08:01
0

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.

souvickcse
  • 7,742
  • 5
  • 37
  • 64
  • @souvickcseThanks but i didnt get ur code properly.. i dont know what are the parameters you r using here..can u explain it.. – Anand Gautam Dec 11 '13 at 09:13
0

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];  
abekenza
  • 1,090
  • 2
  • 11
  • 19
  • Please, change NSData to NSMutableData, and error will disappear. NSMutableData has base64EncodedString method – abekenza Dec 11 '13 at 09:17
  • still it is showing error... i.e. no known instance method for selector base64EncodedString – Anand Gautam Dec 11 '13 at 09:20
  • I have edited my answer, please try it. It has to work – abekenza Dec 11 '13 at 09:26
  • what is customerID, parameter1, customer name and file name? where u r setting tag here ? r u sending image data and text together on server ? – Anand Gautam Dec 11 '13 at 09:35
  • heyy using your above code i am getting returnData 0x1247e5d0 <496d6167 65206973 206e6f74 2055706c 6f6164> but still response string for that response data is showing "Image is not Upload" – Anand Gautam Dec 11 '13 at 10:01
0

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
          }

    }

 }];


 }
Siba Prasad Hota
  • 4,779
  • 1
  • 20
  • 40