我正在尝试使用Objective C中的multipart post请求将两个图像发布到url,从我的代码中,我只能发送一个图像,如何使用multipart / form数据将两个图像发送到url,我已经尝试了很多示例对于这个bur我没有得到我想要的结果

-(void)processPostMultipartRequestNew{
 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

NSString *urlStr =  [self.dataModel.apiUrl
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr = [urlStr
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr= [urlStr stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];



NSURL *reqUrl = [NSURL URLWithString:urlStr];

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



NSDictionary *requestBody = self.dataModel.requestParams2;
UIImage *imageToUpload = [requestBody objectForKey:keyUploadImage];


NSDictionary *requestBody2 = self.dataModel.requestParams;

UIImage *imageToUpload2 = [requestBody2 objectForKey:keyUploadImage];
    if(requestBody){
    NSData *imageData = UIImageJPEGRepresentation(imageToUpload, 0);//no compression by default
    NSData *imageData2 = UIImageJPEGRepresentation(imageToUpload2, 0);

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

    [body appendData:[@"Content-Disposition: attachment; name=\"uploadedfile1\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: attachment; name=\"uploadedfile2\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[NSData dataWithData:imageData2]];

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





    // Text parameter1
    NSString *param1 = @"111";
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"SyncId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


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

    [request setHTTPBody:body];
}

[request setHTTPShouldHandleCookies:NO];
[request setHTTPMethod:REQUEST_TYPE_POST];
[request setTimeoutInterval:60*4];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {


     NSLog(@"completionHandler with response:%@",[NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse*)response statusCode]]);
     NSLog(@"reponse: %ld",(long)[(NSHTTPURLResponse*)response statusCode]);

     NSInteger status = [(NSHTTPURLResponse*)response statusCode];

     if(error){
         NSLog(@"http request error: %@", error.localizedDescription);
         // handle the error
     }
     else{
         if (status == 201){
             // handle the success
         }
         else{
             NSLog(@"error");
         }   // handle the error
     }
     if(!data || data == nil)
         return ;
     NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

     NSDictionary *resultDict  =(NSDictionary *) [NSJSONSerialization
                                                  JSONObjectWithData:data options:NSJSONReadingAllowFragments
                                                  error:&error];

     //NSDictionary *resultDict  =(NSDictionary *) [NSJSONSerialization JSONObjectWithStream:data options:kNilOptions error:&error];

     self.dataModel.responseData =resultDict;
     NSLog(@"error is %@",error);
     NSLog(@"data is %@",data);

     {

     if(!data || data == nil)
         return ;
     NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
     //for failed case
     if(error || error != nil){
         self.dataModel.responseFailed = YES;
         self.dataModel.error = error;
         NSLog(@"Result in error case %@",[[error userInfo] objectForKey:@"NSDebugDescription"]);
         [self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
     }
     else{
         self.dataModel.responseFailed = NO;
         self.dataModel.error = nil;
         NSString  *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         if(!([response rangeOfString:@".jpg"].location==NSNotFound))
         {
             NSString *res=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
             self.dataModel.responseData =res;
             [self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
         }

     }
     }
     self.executing = NO;
     [self setFinishedState:YES];
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

     [self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];

 }];
  }


这是正确的做法吗?如果没有的话,我该如何获得成功。提前致谢。

最佳答案

是的,你可以这样
编辑
///////////////////////////////

      // Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:@"ios" forKey:@"device_type"];
[_params setObject:@"user" forKey:@"type"];
[_params setObject:"iddddd" forKey:@"user_id"];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ


// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@"http........"];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in [_params allKeys]) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add txt data


//////////////////////////////

 NSArray *allImagesData= @[UIImagePNGRepresentation(imageToUpload) ,UIImagePNGRepresentation(imageToUpload2)];

NSLog(@"files array before %@", allImagesData);

for (int i=0; i<[allImagesData count]; i++)
{
    NSString*filename=[NSString stringWithFormat:@"image%d.jpeg",i+1];

    NSString* FileParamConstant = [NSString stringWithFormat:@"image%d",i+1];

    NSData *imageData = allImagesData[i];

    if (imageData)
    {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", FileParamConstant,filename] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

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


}

关于ios - 如何在 objective-c 中使用multipart/formdata发布多个图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48226477/

10-13 04:56