如何使用 post 请求发送多个文件?(目标-c,iOS) [英] How to send multiple files with post request? (objective-c, iOS)

查看:41
本文介绍了如何使用 post 请求发送多个文件?(目标-c,iOS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发送post请求,但我需要发送多个文件,如何做到这一点?

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

tnx

推荐答案

您必须为要上传的不同图像创建边界.让我一步一步解释.1. 将你的图片转换为 NSData 并添加到字典中.

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. 创建上述字典后,就该为请求创建正文部分了.

  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:@"
--%@
", boundary];
[finalPostData appendData:[[NSString stringWithFormat:@"
--%@
", boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];

for(NSString *key in imageDataDictionary)
{
   imageData = [imageDataDictionary objectForKey:key];
   [finalPostData appendData:[[NSString stringWithFormat:@"--%@
", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
   [finalPostData appendData:[@"Content-Disposition: form-data; name="upload"; filename="image.png"
" dataUsingEncoding:NSUTF8StringEncoding]];
   [finalPostData appendData:[@"Content-Type: image/png

" dataUsingEncoding:NSUTF8StringEncoding]];
   [finalPostData appendData:[NSData dataWithData:imageData]];
   [finalPostData appendData:[[NSString stringWithFormat:@"
"] dataUsingEncoding:NSUTF8StringEncoding]];
}

  • 添加所有图像时.我们必须以最终边界结束.

  • When all the images are added. We have to end with final boundary.

    [finalPostData appendData:[[NSString stringWithFormat:@"--%@--
    ", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    

  • 现在我们的数据准备好了.我们只需要将其附加到请求正文中即可.

  • Now our data is ready. We just have to append this to the body of the request.

    这篇关于如何使用 post 请求发送多个文件?(目标-c,iOS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆