Question

In my application i have to upload mutiple images to server using php.

i am making an NSMutableArray *arrImages which hold's my images which are selected from gallery.

suppose if i select two images and try to upload.....i am able to upload only one images which is selected last....i had check my for loop...it's work fine ...but i am not able to upload all two images...please help me out.

following is my code:

- (IBAction)btnTakePicture_Clicked:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Image from..." delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Camera", @"Image Gallary", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    actionSheet.alpha=0.90;
    actionSheet.tag = 1;
    [actionSheet showInView:self.view]; 
    [actionSheet release];
    UIButton *btn = (UIButton *)sender;
    intButton = btn.tag;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (actionSheet.tag) 
    {
        case 1:
            switch (buttonIndex)
        {
            case 0:
            {               
#if TARGET_IPHONE_SIMULATOR

                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Camera not available." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                [alert release];

#elif TARGET_OS_IPHONE  

                UIImagePickerController *picker = [[UIImagePickerController alloc] init];  
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;  
                picker.delegate = self;  
                //picker.allowsEditing = YES;  
                [self presentModalViewController:picker animated:YES];
                [picker release];

#endif  
            }
                break;
            case 1:
            {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];  
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;  
                picker.delegate = self;  
                [self presentModalViewController:picker animated:YES];
                [picker release];
            }
                break;
        }
            break;

        default:
            break;
    }   
}


-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:@"UIImagePickerControllerOriginalImage"],1);
    UIImage *img = [[UIImage alloc] initWithData:dataImage];



    if (intButton == 0) 
    {

        imgView1.image=img;

    }
    else if (intButton == 1) 
    {
        imgView2.image=img;
    }
    else if (intButton == 2) 
    {
        imgView3.image=img;
    }
    else if (intButton == 3)
    {
        imgView4.image=img;

    }
    else if (intButton == 4)
    {
        imgView5.image=img;
    }
    else if (intButton == 5)
    {
        imgView6.image=img;
    }
    else if (intButton ==6)
    {
        imgView7.image=img;
    }
    else if (intButton ==7)
    {
        imgView8.image=img;
    }

    [arrImages addObject:dataImage];
    //NSLog(@"%@",dataImage);
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [self.navigationController dismissModalViewControllerAnimated:YES]; 
}

this is my upload code

-(IBAction)upload:(id)sender
{
    if ([arrImages count]>0) 
    {

        NSString *urlString = @"http://your url.com/upload/uploader.php";

        // setting up the request object now

        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];





        for (int i = 0; i < [arrImages count]; i++)
        {

            //NSMutableData *body = [NSMutableData data];

            //[body appendData:[arrImages objectAtIndex:i] withFileName:@"image.jpg" andContentType:@"image/jpeg" forKey:[NSString stringWithFormat:@"image%d", i + 1]];


            [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    

            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"image%d.jpg\"\r\n",i + 1] dataUsingEncoding:NSUTF8StringEncoding]];

            [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

            //[body appendData:[NSData dataWithData:imageData]];
            [body appendData:[arrImages objectAtIndex:i]];          
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            // setting the body of the post to the reqeust

            //[request setHTTPBody:body];
        }
        [request setHTTPBody:body];

        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

        NSLog(@"%@",returnString);


    }

}

please help me out... i am try this from a long time..

Was it helpful?

Solution

Just a though, you SHOULD NOT use an Array to hold your UIImages. I have serious performance issues with that. What you should do, is to hold an array of paths to the images, on the moment you are going to upload the image, just use the path to get the image. In an iPhone 4 with more than 30 images from the gallery my app started to crash with memory warnings.

Edit (Actual answer for your question):

The problem is that before sending a new upload request, you should wait for the answer of the first. So:

-> upload 1 -> WAIT -> Upload Complete -> upload 2 -> WAIT -> Upload Complete...

Edit 2:

Dimple Panchal is right, you should do it in a asynchronous way.

OTHER TIPS

sendSynchronousRequest Will badly effect your performance since you are including images.. Also I dont think so you should append boundary every time. I dont know much why this is failing but I think structure of your data to be sent is not properly formed. I was unable to add comment so dropped an answer :(

NSString *boundary = [NSString stringWithString:@"------------------------14737829899999999999999999999990"];
    [theRequest addValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];
    [theRequest setHTTPMethod:@"POST"];
NSMutableData *body=[[NSMutableData alloc] init];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"xmldata\"\r\n\r\n %@\r\n\r\n",soapMessage] dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setHTTPBody:body];

Where soap message will contain your data like this loop

 {
  str =[str stringByAppendingString:@"<sampleRoot>"];
  str = [str stringByAppendingFormat:@"<imageDate>%@</imageData>", imgData];
  str =[str stringByAppendingString:@"</sampleRoot>"];

 }
NSString *soapMessage=str;  

This is just the logic, you will need to modify it according to ur requirements.

Asynchronous connections require a bit more code, but are still relatively easy to implement, starting the connection also require a single line of code :

NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

Then we need to implement some callbacks methods

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
  _data = [[NSMutableData alloc] init]; 
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
  [_data appendData:data];
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
  // Handle the error properly
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
   // Deal with the data
}

These wont block ur execution as in synchronousRequest

This is the problem with the code as we are appending the images in the loop the last image is only storing and every time the previous image is overridden by the next image data.I have used AFNetworking Library for sending multiple images to server,its really cool and having all the needs to make the work better and error free.

I think it your your web service problem.please check your service and enable it to receive multiple images.thanks for your code,i was also facing the same problem and now i hope it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top