-(void)uploadPhotoImageWithUrl:(NSString*)url
userIMID:(NSString*)userIMID
imageData:(NSData*)imageData
imageName:(NSString*)imageName{ NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x"; //根据url初始化request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:]; //分界线 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary]; //http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
//参数的集合的所有key的集合 if(imageData){
////添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary]; //声明pic字段,文件名为boris.png
[body appendFormat:@"Content-Disposition: form-data; name="%@"; filename="%@"\r\n",userIMID,imageName];
//声明上传文件的格式
[body appendFormat:@"Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n"];
} //声明结束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData=[NSMutableData data]; //将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
if(imageData){
//将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:@"%ld", (unsigned long)[myRequestData length]]
forHTTPHeaderField:@"Content-Length"]; //设置http body
[request setHTTPBody:myRequestData]; //http method
[request setHTTPMethod:@"POST"]; // URLSession
NSURLSession *session = [NSURLSession sharedSession];
// 上传任务
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request
fromData:myRequestData
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{ if (!data) {
NSString *result = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"%@ %@", result, response);
} else {
NSString *result = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"upload ok! %@ ", result);
}
}]; [task resume]; }