要充分填滿你的要求,你需要發送圖像文件的Web服務使用POST方法
首先選擇圖像從圖片庫或把它從相機,使數據該圖片使用以下代碼。
NSString *imgName = [NSString stringWithFormat:@"ImageTest"];
NSData *imgData=UIImagePNGRepresentation(imgView.image);
NSString* urlstring = [NSString stringWithFormat:@"http://www.example.com/api/create_post/?nonce=eea4bb4ce5&status=publish&title=Test&content=test%20content&categories=animals&imageFile=%@",imgName];
NSLog(@"URL >> %@",urlstring);
NSURL url = [NSURL URLWithString:[urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//===============================================
NSMutableURLRequest postRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[postRequest setURL:url];
[postRequest setHTTPMethod:@"POST"];
NSString boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[postRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [[NSMutableData alloc] init];
[postRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
imgName這是該代碼非常重要對象它您需要在其中如上圖所示Web服務來傳遞圖像。
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.png\"\r\n",imgName]] dataUsingEncoding:NSUTF8StringEncoding]]; //img name
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Add Image imgData is Declare as Above.
[body appendData:[NSData dataWithData:imgData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postRequest setHTTPBody:body];
NSURLResponse *response;
NSError error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error];
NSString *result=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSString * jsonRes = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"result = %@",[result JSONValue]);
它完美地與我合作!我希望你能從這裏得到幫助!