在其中创建带有文件对象的请求字典,稍后 postWith: 函数将处理您的图像绑定任务
NSDictionary *requestDict = [NSDictionary dictionaryWithObjectsAndKeys:@"FirstObjectValue",@"FirstKey",
@"Second Object",@"Second Key",
@"myFileParameterToReadOnServerSide",@"file", nil]; // This line indicate ,POST data has file to attach
[self postWith:requestDict];
如果要发送图像,以下函数将从要发布的对象字典中读取所有参数,然后在字典中添加“文件”键,以标识要随请求发送的文件
- (void)postWith:(NSDictionary *)post_vars
{
NSString *urlString = [NSString stringWithFormat:@"YourHostString"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *boundary = @"----1010101010";
// define content type and add Body Boundry
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSEnumerator *enumerator = [post_vars keyEnumerator];
NSString *key;
NSString *value;
NSString *content_disposition;
while ((key = (NSString *)[enumerator nextObject])) {
if ([key isEqualToString:@"file"]) {
value = (NSString *)[post_vars objectForKey:key];
// *** Write Your Image Name Here ***
// Covnert image to Data and bind to your post request
NSData *postData = UIImageJPEGRepresentation([UIImage imageNamed:@"yourImage"], 1.0);
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\nfilename=\"testUploadFile.jpg\"\r\n\r\n",value] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:postData];
} else {
value = (NSString *)[post_vars objectForKey:key];
content_disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key];
[body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close the request body with Boundry
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField: @"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);
}