iOS 网络编程 - 上传图片到服务器

在网络编程中,如果需要上传图片,那么他的方法将会和普通的上传数据不同,下面将讲解如何上传图片。


环境信息
Mac OS X 10.9.5
Xcode 5.1.1
IOS 7.1

正文:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

- (NSURLRequest *)configPostImageURLWithMethod:(NSString *)method parameters:(NSDictionary *)parameters {
//分界线的标识符
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//根据url初始化request
NSMutableURLRequest* request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:method]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10];
//分界线 --AaB03x
NSString *boundary = [NSStringstringWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary = [NSStringstringWithFormat:@"%@--",boundary];
//要上传的图片
UIImage *image = [parameters objectForKey:@"pic"];
//得到图片的data
NSData* data = UIImagePNGRepresentation(image);
//http body的字符串
NSMutableString *body = [NSMutableStringstring];
//参数的集合的所有key的集合
NSArray *keys = [parameters 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", boundary];
//添加字段名称,换2行
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key];
//添加字段的值
[body appendFormat:@"%@\r\n", [parameters objectForKey:key]];
}
}

////添加分界线,换行
[body appendFormat:@"%@\r\n", boundary];
//声明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 = [NSStringstringWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData = [NSMutableDatadata];
//将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//将image的data加入
[myRequestData appendData:data];
//加入结束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];

//设置HTTPHeader中Content-Type的值
NSString *content = [NSStringstringWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSStringstringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData];
//http method
[request setHTTPMethod:@"POST"];

return request;
}

注:在使用这个方法的时候,图片的key必须是pic。