使用post方法上传文件的两种做法
项目需要使用HTTP协议中的POST方法上传文件,稍微总结了一下,将过程贴出来,方便以后参考。有两种方法,第一是使用NSMutableURLRequest完全从零开始设置,可以加深对HTTP协议的理解;第二种是直接使用别人封装好的代码,如AFNetworking。
方法一,从0开始文件上传NSURL*url=[NSURLURLWithString:@"http://yo.diveinedu.com/upload.php"];NSMutableURLRequest*request=[NSMutableURLRequestrequestWithURL:url];request.HTTPMethod=@"POST";//0.设置分隔符NSString*boundary=@"a1b2c3d4e5f6";[requestsetValue:[NSStringstringWithFormat:@"multipart/form-data;boundary=%@",boundary]forHTTPHeaderField:@"Content-Type"];NSLog(@"%@",request.allHTTPHeaderFields);NSMutableData*httpBody=[NSMutableDatadata];//1.开始的分隔符[httpBodyappendData:[[NSStringstringWithFormat:@"--%@\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];//2.设置内容:标签名,文件名等[httpBodyappendData:[[NSStringstringWithFormat:@"Content-Disposition:form-data;name=\"fileToUpload\";filename=\"%@\"\r\n",@"mask0.png"]dataUsingEncoding:NSUTF8StringEncoding]];NSString*path=[[NSBundlemainBundle]pathForResource:@"mask0"ofType:@"png"];NSLog(@"%@",[selftypeForPath:path]);//3.设置内容格式[httpBodyappendData:[[NSStringstringWithFormat:@"Content-Type:%@\r\n\r\n",[selftypeForPath:path]]dataUsingEncoding:NSUTF8StringEncoding]];NSString*body=[[NSStringalloc]initWithData:httpBodyencoding:NSUTF8StringEncoding];NSLog(@"%@",body);//4.添加真正的内容NSData*data=[NSDatadataWithContentsOfFile:path];[httpBodyappendData:data];//5.添加结束边界[httpBodyappendData:[[NSStringstringWithFormat:@"\r\n--%@--\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];//6.设置httpbodyrequest.HTTPBody=httpBody;//7.发送请求[NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError){NSString*str=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];NSLog(@"%@",str);}];
重点:
注意协议中需要使用回车换行(\r\n)的位置,HTTP是一个基于文本行的协议,通过回车换行来控制格式。
注意分隔符(Boundary)的设置,尤其是(--)的增加。
设置后的内容应该是下面的样子(为了看得更清楚,将回车换行用文字表示出来了):
POST/upload.phpHTTP/1.1\r\nHost:yo.diveinedu.com\r\nContent-Type:multipart/form-data;boundary=abcdefghigk\r\n\r\nContent-Disposition:form-data;name="fileToUpload";filename="mask0.png"\r\nContent-Type:p_w_picpath/png\r\n\r\n--abcdefghigk\r\n图片数据\r\n--abcdefghigk--\r\n方法二,使用AFNetworking中的方法
AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManagermanager];manager.responseSerializer=[AFHTTPResponseSerializerserializer];[managerPOST:@"http://yo.diveinedu.com/upload.php"parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData>formData){//1.方法一//NSError*error;//if(![formDataappendPartWithFileURL:[NSURLfileURLWithPath:path]name:@"fileToUpload"fileName:[pathlastPathComponent]mimeType:@"p_w_picpath/png"error:&error]){//NSLog(@"errorappendingpart:%@",error);//}//2.方法二NSData*data=[NSDatadataWithContentsOfFile:path];[formDataappendPartWithFileData:dataname:@"fileToUpload"fileName:[pathlastPathComponent]mimeType:@"p_w_picpath/png"];}success:^(AFHTTPRequestOperation*operation,idresponseObject){NSData*data=(NSData*)responseObject;NSString*str=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];NSLog(@"%@",str);}failure:^(AFHTTPRequestOperation*operation,NSError*error){NSLog(@"%@",error);}];
进行网络编程的时候,可以使用Wireshark之类的抓包工具辅助调试。可以很明确的看到发送或接收的数据是否正确。
最后祝大家儿童节快乐~~~
http://io.diveinedu.com
http://www.diveinedu.com
http://bbs.diveinedu.com
https://github.com/DiveinEdu-CN
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。