post上传图片到服务器
这几天,项目需要将图片,音频文件(如mp3)上传到服务器,以方便之后的使用。在网上查询了很多资料,一般有以下几种方式,1.ASIHTTPRequest 方式
2. AFNetWorking方式,3. ASIFormDataRequest方式 4 .NSMutableURLRequest方式。前面3种方式都需要加载对应的库或者第3方库,我并没有搞出来。所以现在就第3种方式进行说明。
JAVA可以使用表单方式直接上传图片,音频等等。但IOS并没有提供类似的方式,如果要使用的话,就需要模拟出类似的post请求,java段post源代码为:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Form Page</title> </head> <body> <h1>Upload a File</h1> <form action="http://192.168.2.153:28080/upload" method="post" enctype="multipart/form-data"> <p> Select a file : <input type="file" name="file" size="50" /> </p> <input type="submit" value="Upload It" /> </form> </body> </html>
以下是我封装的代码,参考网上进行修改的:
+(NSString*)uploadImage:(NSString*)url param:(NSMutableDictionary*)params format:(NSString*)fmat { //分界线的标识符 NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x"; //根据url初始化request NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10]; //分界线 --AaB03x NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY]; //结束符 AaB03x-- NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary]; //要上传的图片 UIImage *image=[UIImage imageNamed:[params objectForKey:@"pic"]]; //得到图片的data NSData* data = UIImagePNGRepresentation(image); //http body的字符串 NSMutableString *body=[[NSMutableString alloc]init]; //参数的集合的所有key的集合 NSArray *keys= [params allKeys]; //遍历keys for(int i=0;i<[keys count];i++) { //得到当前key NSString *key=[keys objectAtIndex:i]; //如果key不是pic,说明value是字符类型,比如name:Boris if(![key isEqualToString:@"pic"]) { //添加分界线,换行 [body appendFormat:@"%@\r\n",MPboundary]; //添加字段名称,换2行 [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key]; //添加字段的值 [body appendFormat:@"%@\r\n",[params objectForKey:key]]; } } ////添加分界线,换行 [body appendFormat:@"%@\r\n",MPboundary]; //声明pic字段,文件名为boris.png //[body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"text02.png\"\r\n"]; [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",FORM_FLE_INPUT,[params objectForKey:@"pic"]]; //声明上传文件的格式 //[body appendFormat:@"Content-Type: image/png,image/jpeg\r\n\r\n"]; NSString *contype = [NSString stringWithFormat:@"Content-Type: %@\r\n\r\n",fmat]; NSLog(@"content type=%@",contype); [body appendFormat:@"Content-Type: %@\r\n\r\n",fmat]; //声明结束符:--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]; //设置HTTPHeader [request setValue:content forHTTPHeaderField:@"Content-Type"]; //设置Content-Length [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"]; //设置http body [request setHTTPBody:myRequestData]; //http method [request setHTTPMethod:@"POST"]; //建立连接,设置代理 NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; //设置接受response的data if (conn) { NSLog(@"connect successs"); NSHTTPURLResponse *urlResponese = nil; NSError *error; NSData* resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponese error:&error]; NSString* result= [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding]; NSLog(@"error=%@",[error localizedFailureReason]); NSLog(@"返回结果=====%@ resuct code=%d ",result,[urlResponese statusCode]); return result; } return nil; }
调用的方式如下:
NSMutableDictionary *pa = [NSMutableDictionary dictionaryWithCapacity:1]; [pa setValue:@"view1.jpg" forKey:@"pic"]; [pa setValue:@"view1" forKey:@"field1"]; //[pa setValue:@"jpeg" forKey:@"format"]; NSString* result = [具体类 uploadImage: urlstring param:pa format:@"image/jpeg"]; NSLog(@"result = %@",result);
第一个参数为上传服务器的ip地址字符串,第2个参数为body值参数,根据具体情况可能有所不同,第3个参数为上传图片的格式。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。