multipart/from-data是一种进行表单提交时的消息格式。表单提交数据的时候,默认类型是application/x-www-form-urlencoded,也就是key=value的键值对格式,提交文件的时候使用multipart/from-data。因为是表单提交,所以http请求方式是POST。然后在请求头里设置Content-Type为multipart/from-data指定请求的格式。后附有使用第三方AFNetWorking上传报文的方法
NSURL *URL = [[NSURL alloc]initWithString:urlString];
request = [[NSMutableURLRequest alloc]initWithURL:URL cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30];
request.HTTPMethod = @"POST";
NSString *boundary = @"wfWiEWrgEFA9A78512weF7106A";
request.allHTTPHeaderFields = @{
@"Content-Type":[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]
};
注意到在Content-Type里还有个boundary,这个是用来做分隔的字符串。boundary本身没有特殊要求,只要不会和其他内容混淆就好。
整合代码:
static NSString *boundary=@"xdxd2313132331221232Request";
- (NSMutableURLRequest *)requestWithURL:(NSURL *)url andFilenName:(NSString *)fileName andLocalFilePath:(NSString *)localFilePath{
//post请求
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:2.0f];
request.HTTPMethod=@"POST";//设置请求方法是POST
request.timeoutInterval=60.0;//设置请求超时
//拼接请求体数据(0-6步)
NSMutableData *requestMutableData=[NSMutableData data];
//0.拼接参数
/*--------------------------------------------------------------------------*/
NSDictionary *params = @{
@"param1" : @"XXX",
@"param2" :@"XXX"
};
for (NSString *key in params) {
NSString *pair = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n",boundary,key];
[requestMutableData appendData:[pair dataUsingEncoding:NSUTF8StringEncoding]];
id value = [params objectForKey:key];
if ([value isKindOfClass:[NSString class]]) {
[requestMutableData appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
}else if ([value isKindOfClass:[NSData class]]){
[requestMutableData appendData:value];
}
[requestMutableData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
/*--------------------------------------------------------------------------*/
//1.\r\n--Boundary+72D4CD655314C423\r\n // 分割符,以“--”开头,后面的字随便写,只要不写中文即可
NSMutableString *myString=[NSMutableString stringWithFormat:@"\r\n--%@\r\n",boundary];
//2. Content-Disposition: form-data; name="image"; filename="001.png"\r\n // 这里注明服务器接收图片的参数(类似于接收用户名的userName)及服务器上保存图片的文件名
[myString appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n",fileName]];
//3. Content-Type:image/png \r\n // 图片类型为png
[myString appendString:[NSString stringWithFormat:@"Content-Type:application/octet-stream\r\n"]];
//4. Content-Transfer-Encoding: binary\r\n\r\n // 编码方式
[myString appendString:@"Content-Transfer-Encoding: binary\r\n\r\n"];
//转换成为二进制数据
[requestMutableData appendData:[myString dataUsingEncoding:NSUTF8StringEncoding]];
//5.文件数据部分
NSURL *filePathUrl=[NSURL URLWithString:localFilePath];
//转换成为二进制数据
[requestMutableData appendData:[NSData dataWithContentsOfURL:filePathUrl]];
//6. \r\n--Boundary+72D4CD655314C423--\r\n // 分隔符后面以"--"结尾,表明结束
[requestMutableData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
/*--------------------------------------------------------------------------*/
//设置请求体
request.HTTPBody=requestMutableData;
//设置请求头
NSString *headStr=[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request setValue:headStr forHTTPHeaderField:@"Content-Type"];
return request;
}
调用:
NSMutableURLRequest *request=[self requestWithURL:[NSURL URLWithString:@"https://xxx.xxx.xxx"] andFilenName:@"image.png" andLocalFilePath:[[NSUserDefaults standardUserDefaults] objectForKey:@"PIC_DATA"]];
//连接(NSURLSession)
NSURLSession *session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
[SVProgressHUD dismiss];
id result=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"post==%@",result);
[SVProgressHUD showSuccessWithStatus:result[@"result_msg"]];
if (result[@"result_code"]) {
[self.navigationController popViewControllerAnimated:YES];
}
}];
[dataTask resume];
附加:使用AFNetworking框架上传http multipart/form-data参数
#import <AFHTTPSessionManager.h>
NSDictionary *params = @{
@"param1" : @"xxx";
@"param2" :@"xxx"
};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
@"text/html",
@"image/jpeg",
@"image/png",
@"application/octet-stream",
@"text/json",
nil];
[manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
[manager POST:@"https://www.xxx.com" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//给定数据流的数据名,文件名,文件类型(以图片为例)
[formData appendPartWithFileData:_iconData name:@"image" fileName:@"image.png" mimeType:@"image/png"];
/*常用数据流类型:
@"image/png" 图片
@“video/quicktime” 视频流
*/
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[SVProgressHUD dismiss];
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSLog(@"resDict:%@",resDict);
NSString *result_code = [resDict objectForKey:@"result_code"];
if ([result_code isEqual:@"SUCCESS"]) {
[self.navigationController popViewControllerAnimated:YES];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error:%@",error);
}];
网友评论