如何通过服务器上的数组上传图像?

时间:2012-01-04 08:13:20

标签: iphone objective-c ios ios4 xcode3.2

在我的应用程序中,我必须使用php将多个图像上传到服务器。

我正在制作一张NSMutableArray * arrImages,其中包含从图库中选择的图像。

假如我选择了两张图片并尝试上传.....我只能上传最后选择的一张图片....我已经检查了我的循环...它的工作正常......但是我无法上传所有两张图片...请帮帮我。

以下是我的代码:

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

这是我的上传代码

-(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);


    }

}

请帮帮我...我很长时间试试这个......

4 个答案:

答案 0 :(得分:3)

但是,不应该使用数组来保存UIImages。我有严重的性能问题。您应该做的是保存一系列图像路径,在您要上传图像的那一刻,只需使用路径获取图像。在带有超过30张图片的iPhone 4中,我的应用程序开始出现内存警告崩溃。

修改(问题的实际答案):

问题是在发送新的上传请求之前,您应该等待第一个的回答。所以:

- &GT;上传1 - &gt;等待 - &gt;上传完成 - &gt;上传2 - &gt;等待 - &gt;上传完成...

编辑2:

Dimple Panchal是对的,你应该以异步方式进行。

答案 1 :(得分:1)

sendSynchronousRequest因为你要包含图片,会严重影响你的表现。 我也不这么认为你应该每次追加边界。我不知道为什么这会失败,但我认为要发送的数据结构没有正确形成。我无法添加评论所以放弃了答案:(

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

soap消息将包含您的数据 循环

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

 }
NSString *soapMessage=str;  

这只是逻辑,你需要根据你的要求修改它。

异步连接需要更多代码,但仍然相对容易实现,启动连接也需要一行代码:

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

然后我们需要实现一些回调方法

-(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
}

这些不会像synchronousRequest

那样阻止你的执行

答案 2 :(得分:0)

这是代码的问题,因为我们将图像附加到循环中,最后一个图像仅存储,每次上一个图像被下一个图像数据覆盖。我使用AFNetworking Library将多个图像发送到服务器,它非常酷,并且具备使工作更好,没有错误的所有需求。

答案 3 :(得分:-1)

我认为这是您的Web服务问题。请检查您的服务并使其能够接收多个images.thanks代码,我也面临同样的问题,现在我希望它有效。