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];
//設(shè)置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",boundary];
//設(shè)置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//設(shè)置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打碼失敗結(jié)果
}
}
}] resume];
//此處image是在項(xiàng)目中自取的image,讀者注意自己拿到圖片的方式,測(cè)試的話可以在項(xiàng)目中加入一張11.png的圖片
UIImage *image = [UIImage imageNamed:@"11.png"];
//此處是對(duì)圖片進(jìn)行壓縮,壓縮的 比例是公司自己對(duì)于上傳圖片的標(biāo)準(zhǔn)要求
NSData *imageData = UIImageJPEGRepresentation(image, 0.000001);
//此處url為讀者公司自己的服務(wù)器url
NSString *url = @"------------------";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:30];
request.HTTPMethod = @"POST";
//分界線的標(biāo)識(shí)符
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//分界線 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//結(jié)束符 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(@"網(wǎng)絡(luò)請(qǐng)求body:%@",body);
//聲明結(jié)束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//聲明myRequestData,用來(lái)放入http body
NSMutableData *myRequestData=[NSMutableData data];
//將body字符串轉(zhuǎn)化為UTF8格式的二進(jìn)制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//將image的data加入
[myRequestData appendData:imageData];
//加入結(jié)束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//設(shè)置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//設(shè)置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//設(shè)置Content-Length
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//設(shè)置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) {
//網(wǎng)絡(luò)請(qǐng)求失敗
if (error != nil) {
return;
}
//成功進(jìn)行解析
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];