How to send multiple files with post request? (objective-c, iOS)

后端 未结 2 1588
醉话见心
醉话见心 2021-01-23 18:21

I want to sent post request, but i need to send multiple files, how to do this?

tnx

相关标签:
2条回答
  • 2021-01-23 19:03

    Use one of the many resources on how to configure an NSMutableURLRequest for POSTing data. The Content-Type header should be "multipart/form-data", and each file will be concatenated in turn with an appropriate part header. RFC2388 is the relevant standard.

    0 讨论(0)
  • 2021-01-23 19:05

    You have to create boundaries for different images to be uploaded. Let me explain step by step. 1. Convert your images to NSData and add them to dictionary.

        UIImage *image1 = [UIImage imageNamed:@"imageName"];        
        UIImage *image2 = [UIImage imageNamed:@"imageName"];       
        UIImage *image3 = [UIImage imageNamed:@"imageName"];
    
        NSMutableDictionary *imageDataDictionary = [[NSMutableDictionary alloc] init];
        [imageDataDictionary setObject:UIImagePNGRepresentation(image1) forKey:@"image"];
        [imageDataDictionary setObject:UIImagePNGRepresentation(image2) forKey:@"image"];
        [imageDataDictionary setObject:UIImagePNGRepresentation(image3) forKey:@"image"];
    
    1. When you have created the above dictionary its time to create body part for the request.

      NSMUtableData *finalPostData = [[NSMutableData alloc] init];
      NSString *boundary = @"0xKhTmLbOuNdArY";
      NSString *endBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary];
      [finalPostData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
      contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
      
      for(NSString *key in imageDataDictionary)
      {
         imageData = [imageDataDictionary objectForKey:key];
         [finalPostData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
         [finalPostData appendData:[@"Content-Disposition: form-data; name=\"upload\"; filename=\"image.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
         [finalPostData appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
         [finalPostData appendData:[NSData dataWithData:imageData]];
         [finalPostData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
      }
      
    2. When all the images are added. We have to end with final boundary.

      [finalPostData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
      
    3. Now our data is ready. We just have to append this to the body of the request.

    0 讨论(0)
提交回复
热议问题