//分界線的標識符 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=[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=\"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]; //設定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]; //設定接受resp*****e的data if (conn) { mResp*****eData = [[NSMutableData data] retain]; }