參加工作也有一段時(shí)間了,自己覺(jué)得是時(shí)候?qū)ψ约汗ぷ鞯慕?jīng)驗(yàn)做一點(diǎn)總結(jié)了,也是為了以后閑時(shí)能看看自己的成長(zhǎng)吧亭螟。所以,是時(shí)候?qū)扅c(diǎn)什么了阶女。
通過(guò)Http上傳文件
因?yàn)閕OS不能通過(guò)html表單來(lái)進(jìn)行post上傳,所以iOS想要完成上傳功能就要自己實(shí)現(xiàn)http請(qǐng)求
http post請(qǐng)求的格式是這樣的
Content-type:multipart/formdata, boundary=boundary
--boundary
Content-disposition: form-data; name="name"
mike
--boundary
Content-disposition: form-data; name: "pic", filename: "myPic.jpg"
Content-type: image/jpg
<myPic.jpg>
--boundary--
這就是我們上傳時(shí)需要配置的http
boundary
規(guī)定的是什么,后面就要一樣杨名。boundary
是分割各個(gè)參數(shù)的分隔符。 注意:boundary
結(jié)尾時(shí),是--boundary--
,代表請(qǐng)求體結(jié)束仁堪。multipart/formdata
上傳的請(qǐng)求頭必須包含一個(gè)特殊的信息:Content-type
其值也必須是multipart/formdata
如果是一個(gè)文件則需要文件信息filename:"myPic.jpg"
與文件內(nèi)容類型Content-type:image/jpg
,<myPic.jpg>
則是我們想要上傳的圖片或者文件球匕。
一定要嚴(yán)格按照規(guī)則,否則不會(huì)成功
下面是iOS實(shí)現(xiàn)代碼:
NSDictionary *param = @{@"name":@"mike"};
NSString *TWITTERFON_FORM_BOUNDARY = @"12344321";
NSMutableURLRequest *mulrequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http"] cachePolicy:(NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:10];
NSString *boundary = [NSString stringWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
NSString *endBoundary = [NSString stringWithFormat:@"--%@--",TWITTERFON_FORM_BOUNDARY];
UIImage *image = [UIImage imageNamed:@"pic"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.3);
NSMutableString *body = [NSMutableString string];
NSArray *keys = [param allKeys];
for (NSString *key in keys) {
[body appendFormat:@"%@\r\n",boundary];
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
[body appendFormat:@"%@\r\n",[dic objectForKey:key]];
}
[body appendFormat:@"%@\r\n",boundary];
[body appendFormat:@"Content-Disposition:form-data; name=\"pic\"; filename=\"myPic.jpg\"\r\n"];
[body appendFormat:@"Cotent-Type: image/png"];
NSMutableData *requestData = [NSMutableData data];
[requestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
[requestData appendData:imageData];
[requestData appendData:[[NSString stringWithFormat:@"\r\n%@",endBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *content = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
[mulrequest setValue:content forHTTPHeaderField:@"Content-Type"];
[mulrequest setValue:[NSString stringWithFormat:@"%lu", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[mulrequest setHTTPBody:requestData];
[mulrequest setHTTPMethod:@"POST"];
NSURLSessionConfiguration *sessionCon = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionCon];
NSURLSessionDataTask *task = [session dataTaskWithRequest:mulrequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"complite");
}];
[task resume];
AFN上傳
通常,我們并不需要配置如此麻煩的東西.因?yàn)榭傆幸恍┐笊駚?lái)幫助我們.我們熟悉的AFN框架就很好的解決這些麻煩的配置問(wèn)題,這一章主要來(lái)看看如何通過(guò)AFN來(lái)實(shí)現(xiàn)文件上傳.在下一章,會(huì)對(duì)AFN的主要源碼進(jìn)行分析,敬請(qǐng)期待
AFN代碼如下
AFHTTPSessionManager *sharedManager1 = [[AFHTTPSessionManager alloc]init];
sharedManager1.requestSerializer = [AFHTTPRequestSerializer serializer];
sharedManager1.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
sharedManager1.requestSerializer.timeoutInterval =20;
[sharedManager1.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[sharedManager1.requestSerializer setValue:@"text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSDictionary *dic = @{@"param.token":_token};
[sharedManager1 POST:kUploadFile parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
for (int i = 0; i < fileUpload.count; i ++) {
NSData *data = UIImageJPEGRepresentation(fileUpload[i], 0.3);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 設(shè)置時(shí)間格式
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@-%@.jpeg", str,[NSString stringWithFormat:@"%d",i]];
[formData appendPartWithFileData:data name:@"fileUpload" fileName:fileName mimeType:@"image/jpeg"];
}
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
success(task,responseObject);
} failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
fail(task,error);
}];
我們?cè)谏蟼鲌D片是需要對(duì)圖片進(jìn)行壓縮編碼,通常是使用UIImageJPEGRepresentation(,)
方法 float
數(shù)一般是0.3~0.5
其他上傳方式
當(dāng)然,系統(tǒng)的NSURLSession
類提供了專門上傳的方法
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request;
AFN的上傳就是基于這個(gè)方法完成的,有興趣的可以百度了解一下,下一節(jié)我會(huì)對(duì)AFN的主要源碼進(jìn)行分析