NSURLSession, form-data 上传
NSString *urlString = @"";
NSURL *url = [NSURL URLWithString:urlString];
NSData *imageData = [NSData dataWithContentsOfURL:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://api.yundama.com/api.php?method=upload"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSArray *parameters = @[];
NSString *boundary = @"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:@"--%@\r\n", boundary];
if (param[@"fileName"]) {
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
formatter.dateFormat=@"yyyyMMddHHmmss";
NSString *str=[formatter stringFromDate:[NSDate date]];
NSString *fileName=[NSString stringWithFormat:@"%@.gif",str];
NSLog(@"file name : %@",fileName);
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], fileName];
[body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]];
if (error) {
NSLog(@"%@", error);
}
} else {
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]];
[body appendFormat:@"%@\n", param[@"value"]];
}
}
NSString *end = [NSString stringWithFormat:@"\r\n--%@--\r\n",boundary];
NSMutableData *requestData = [NSMutableData data];
[requestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
[requestData appendData:imageData];
[requestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:requestData];
//设置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",boundary];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"error : %@",error);
[self postYunDaMaFail];
} else {
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
} else {
//post打码失败结果
}
}
}] resume];
//此处image是在项目中自取的image,读者注意自己拿到图片的方式,测试的话可以在项目中加入一张11.png的图片
UIImage *image = [UIImage imageNamed:@"11.png"];
//此处是对图片进行压缩,压缩的 比例是公司自己对于上传图片的标准要求
NSData *imageData = UIImageJPEGRepresentation(image, 0.000001);
//此处url为读者公司自己的服务器url
NSString *url = @"------------------";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:30];
request.HTTPMethod = @"POST";
//分界线的标识符
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//分界线 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
/*
上传格图片格式:
--AaB03x
Content-Disposition: form-data; name="file"; filename="currentImage.png"
Content-Type: image/png
*/
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
// //添加分界线,换行
// [body appendFormat:@"%@\r\n",MPboundary];
//添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//声明file字段,文件名为currentImage.png
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
formatter.dateFormat=@"yyyyMMddHHmmss";
NSString *str=[formatter stringFromDate:[NSDate date]];
NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
[body appendFormat:@"%@", [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",fileName]];
//声明上传文件的格式
[body appendFormat:@"Content-Type: image/jpg\r\n\r\n"];
NSLog(@"网络请求body:%@",body);
//声明结束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData=[NSMutableData data];
//将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//将image的data加入
[myRequestData appendData:imageData];
//加入结束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//设置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData];
// NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//网络请求失败
if (error != nil) {
return;
}
//成功进行解析
NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"%@--%@",dic, response);
}];
[task resume];
base64 上传
NSURL *damaURL = [NSURL URLWithString:[NSString stringWithFormat:@""]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:damaURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
request.HTTPMethod = @"POST";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// [request setValue:@"Bearer 9b1d173066bf4d32b9e1d0259d2fc26c" forHTTPHeaderField:@"Authorization"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@""]];
NSString *base64Image = [data base64EncodedStringWithOptions:0];
NSDictionary *json = @{@"img_data":base64Image};
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
// NSString *parms = [NSString stringWithFormat:@"img_data=%@", base64Image];
// request.HTTPBody = [parms dataUsingEncoding:NSUTF8StringEncoding];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"MFLog: post image error - %@",error);
} else {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
}
}] resume];