欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS通过http post上传图片

程序员文章站 2023-11-04 13:37:16
本文实例为大家分享了ios通过http post上传图片的相关代码,供大家参考,具体内容如下 //asiformdatarequest方式 post上传图片 -...

本文实例为大家分享了ios通过http post上传图片的相关代码,供大家参考,具体内容如下

//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;
//添加拍照图
//分界线的标识符
nsstring *twitterfon_form_boundary = @"aab03x";
//分界线 --aab03x
nsstring *mpboundary=[[nsstring alloc]initwithformat:@"--%@",twitterfon_form_boundary];
//结束符 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];
//参数的集合的所有key的集合
nsarray *keys= [sugestdic allkeys];
//遍历keys
for(int i=0;i<[keys count];i++)
{
//得到当前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"];
}
//声明结束符:--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:data];
//加入结束符--aab03x--
[myrequestdata appenddata:[end datausingencoding:nsutf8stringencoding]];
//设置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:)];
// 解析取得的结果
return tempdic;
}

以上就是本文的全部内容,希望对大家的学习有所帮助。