iOS通過http post上傳圖片
更新時間:2016年03月17日 11:38:08 作者:小貝
這篇文章主要介紹了iOS通過http post上傳圖片的相關(guān)資料,需要的朋友可以參考下
本文實例為大家分享了iOS通過http post上傳圖片的相關(guān)代碼,供大家參考,具體內(nèi)容如下
//ASIFormDataRequest方式 POST上傳圖片
-(NSDictionary *)addPicWithDictionary:(NSDictionary *)sugestDic{
NSDictionary *tempDic=nil;
NSString *url=[NSString stringWithFormat:@"http://182.50.0.62:8095/xianServer/upload/uploadImage?clientType=mobile"];
form = [[[ASIFormDataRequest alloc]
initWithURL:[NSURL URLWithString:url]] autorelease];
[form setTimeOutSeconds:60.0];
form.delegate = self;
//添加拍照圖
//分界線的標(biāo)識符
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//分界線 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//結(jié)束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
//添加拍照圖片
imageView.image=[UIImage imageNamed:@"btn_done_down@2x.png"];
NSData* data = UIImagePNGRepresentation(imageView.image);
NSLog(@"%@",data);
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
//參數(shù)的集合的所有key的集合
NSArray *keys= [sugestDic allKeys];
//遍歷keys
for(int i=0;i<[keys count];i++)
{
//得到當(dāng)前key
NSString *key=[keys objectAtIndex:i];
//如果key不是pic,說明value是字符類型,比如name:Boris
if(![key isEqualToString:@"files"])
{
//添加分界線,換行
[body appendFormat:@"%@\r\n",MPboundary];
//添加字段名稱,換2行
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
//添加字段的值
[body appendFormat:@"%@\r\n",[sugestDic objectForKey:key]];
}
}
if (imageView.image) {
////添加分界線,換行
[body appendFormat:@"%@\r\n",MPboundary];
//聲明pic字段,文件名為boris.png
[body appendFormat:@"Content-Disposition: form-data; name=\"files\"; filename=\"boris.png\"\r\n"];
//聲明上傳文件的格式
[body appendFormat:@"Content-Type: image/png\r\n\r\n"];
}
//聲明結(jié)束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//聲明myRequestData,用來放入http body
NSMutableData *myRequestData=[NSMutableData data];
//將body字符串轉(zhuǎn)化為UTF8格式的二進(jìn)制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//將image的data加入
[myRequestData appendData:data];
//加入結(jié)束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//設(shè)置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
[form addRequestHeader:@"Content-Type" value:content];
[form addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%d", [myRequestData length]]];
[form setRequestMethod:@"POST"];
[form startAsynchronous];
[form setDidFailSelector:@selector(requestBeFailed:)];
[form setDidFinishSelector:@selector(requestBeFinished:)];
// 解析取得的結(jié)果
return tempDic;
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
全面解析iOS應(yīng)用中自定義UITableViewCell的方法
這篇文章主要介紹了iOS應(yīng)用開發(fā)中自定義UITableViewCell的方法,示例為傳統(tǒng)的Obejective-C語言,需要的朋友可以參考下2016-04-04

