参加工作也有一段时间了,自己觉得是时候对自己工作的经验做一点总结了,也是为了以后闲时能看看自己的成长吧。所以,是时候写点什么了。
通过Http上传文件
因为iOS不能通过html表单来进行post上传,所以iOS想要完成上传功能就要自己实现http请求
http post请求的格式是这样的
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--
这就是我们上传时需要配置的http
boundary
规定的是什么,后面就要一样。boundary
是分割各个参数的分隔符。 注意:boundary
结尾时,是--boundary--
,代表请求体结束。multipart/formdata
上传的请求头必须包含一个特殊的信息:Content-type
其值也必须是multipart/formdata
如果是一个文件则需要文件信息filename:"myPic.jpg"
与文件内容类型Content-type:image/jpg
,<myPic.jpg>
则是我们想要上传的图片或者文件。
一定要严格按照规则,否则不会成功
下面是iOS实现代码:
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上传
通常,我们并不需要配置如此麻烦的东西.因为总有一些大神来帮助我们.我们熟悉的AFN框架就很好的解决这些麻烦的配置问题,这一章主要来看看如何通过AFN来实现文件上传.在下一章,会对AFN的主要源码进行分析,敬请期待
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];
// 设置时间格式
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);
}];
我们在上传图片是需要对图片进行压缩编码,通常是使用UIImageJPEGRepresentation(,)
方法 float
数一般是0.3~0.5
其他上传方式
当然,系统的NSURLSession
类提供了专门上传的方法
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request;
AFN的上传就是基于这个方法完成的,有兴趣的可以百度了解一下,下一节我会对AFN的主要源码进行分析