如何将多部分表单中的多个图像文件发送到服务器?

时间:2017-05-17 09:59:08

标签: ios objective-c xcode multipart

  

我正在使用此代码并且只能将单个图像发送到服务器。一世     想要将多个选定的图像文件发送到服务器。   请查看此代码是否存在错误,请帮助我     出来解决这个问题。感谢您的时间。

-(void)submitDataToServer
 {

NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];

NSNumber *randomNo = [NSNumber numberWithInteger: timeStamp];

NSLog(@"Random No=%@",randomNo);
NSLog(@"Project ID=%@",projectId);
NSLog(@"DATE=%@",dateString);
NSLog(@"USER ID=%@",userID);
NSLog(@"COMMENT =%@",projectNoteTextView.text);
NSLog(@"TASK ID=%@",task_Id);


//-- Convert string into URL
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL  URLWithString:UPLOADDATA_URL]];

[request setHTTPMethod:@"POST"];
NSString *boundary = @"14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

//-- Append data into posr url using following method
NSMutableData *body = [NSMutableData data];

//Random No
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"random"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",randomNo] dataUsingEncoding:NSUTF8StringEncoding]];

//Project ID
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"project_id"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",projectId] dataUsingEncoding:NSUTF8StringEncoding]];

//Date
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"date"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",dateString] dataUsingEncoding:NSUTF8StringEncoding]];

//User ID
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"user_id"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",userID] dataUsingEncoding:NSUTF8StringEncoding]];

//Comment
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"comment"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",projectNoteTextView.text] dataUsingEncoding:NSUTF8StringEncoding]];

//Task ID
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"task_assign_id"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",task_Id] dataUsingEncoding:NSUTF8StringEncoding]];


NSLog(@"ARRAYCOUNT: %lu", (unsigned long)arrImage.count);
for (int y = 0; y < [arrImage count]; y++)
{
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    NSString * image_name =[NSString stringWithFormat:@"%@%d",@"image",y];
    NSLog(@"IMAGE NAME:%@", image_name);   //self.arrImage

    UIImage*  imageFile = [arrImage objectAtIndex:y];

    CGSize newSize = CGSizeMake(500.0f, 500.0f);
    UIGraphicsBeginImageContext(newSize);
    [imageFile drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

     NSData *dataImg = [NSData 
     dataWithData:UIImagePNGRepresentation(newImage)];

  //NSData *dataImg = [NSData dataWithData:UIImagePNGRepresentation([arrImage objectAtIndex:y])]; 

    NSLog(@"added %i", y+1);
    NSLog(@"Images, send to server:%@", dataImg);

    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"site_image\"; filename=\"%@\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:dataImg]];
}
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//-- Sending data into server through URL
[request setHTTPBody:body];

//-- Getting response form server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"Result = %@",result);
}

2 个答案:

答案 0 :(得分:1)

for loop中的此代码用于多张图片。

dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"imgProfile"];

        NSString *str=[NSString stringWithFormat:@"%@",yourUrl];
        NSString *urlString = [NSString stringWithFormat:@"%@",str];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];
        NSMutableData *body = [NSMutableData data];
        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Disposition: form-data; name=\"profilePicture\"; filename=\"ved.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //  parameter image

        if (imageData.length<1) {

            [body appendData:[@" " dataUsingEncoding:NSUTF8StringEncoding]];

        }
        else {
        [body appendData:[NSData dataWithData:imageData]];
        }
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //  parameter Method

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"method\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[@"profileUpdate" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


        //  parameter userID
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"]] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //userId , email , name , tockenId , deviceType , cCode,profilePicture,phone

        //parameter email
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[txtEmail.text dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //  parameter name
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[[NSString stringWithFormat:@"%@",txtName.text] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //parameter tockenId

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"tockenId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"Device_Token"]] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        // Parameter deviceType


        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"deviceType\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[[NSString stringWithFormat:@"%@",@"iOS"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

               //parameter  cCode

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

        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"cCode\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[txtCountryCode.text dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


//        //parameter profilePicture
//        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"profilePicture\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//        
//        [body appendData:[@"ved" dataUsingEncoding:NSUTF8StringEncoding]];
//        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //parameter phone

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

        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"phone\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[txtPhone.text dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];



        // close form
        [body appendData:[[NSString stringWithFormat:@"--%@--\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];
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"Update profile Image %@",dict);


        dispatch_async(dispatch_get_main_queue(), ^{


            if ([[dict valueForKey:@"result"] isEqualToString:@"sucess"]) {

                [WebServiceHelper showAlertViewForTitle:@"Message" andMessage:[dict valueForKey:@"message"]];


            }
            else{


                [WebServiceHelper showAlertViewForTitle:@"Updating Failed!" andMessage:[dict valueForKey:@"message"]];
            }


        });



    });
}

答案 1 :(得分:0)

  

重新检查后,我知道我传递了错误的图像阵列。现在改变之后这个工作正常。谢谢大家的时间和考虑。

NSLog(@"ARRAYCOUNT: %lu", (unsigned long)imgArray.count);
for (int y = 0; y < [arrImage count]; y++)
{
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

NSString * image_name =[NSString stringWithFormat:@"%@%d",@"image",y];
NSLog(@"IMAGE NAME:%@", image_name);

UIImage*  imageFile = [arrImage objectAtIndex:y];

CGSize newSize = CGSizeMake(500.0f, 500.0f);
UIGraphicsBeginImageContext(newSize);
[imageFile drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

 NSData *dataImg = [NSData 
 dataWithData:UIImagePNGRepresentation(newImage)];

 //NSData *dataImg = [NSData dataWithData:UIImagePNGRepresentation([imgArray objectAtIndex:y])]; 

NSLog(@"added %i", y+1);
NSLog(@"Images, send to server:%@", dataImg);

[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"site_image\"; filename=\"%@\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:dataImg]];
  

块引用

}