原始方式文件上传的步骤:
1、创建POST请求
NSURL *url = [NSURL URLWithString:@"文件上传到服务器的Url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
2、设置请求头(告诉告诉服务器,这是一个文件上传的请求)
①非文件参数(普通的用户名账户和密码等参数)
--本次文件上传的标识字符串\r\n
Content-Disposition: form-data; name="参数名"\r\n
\r\n
参数值
\r\n
②文件参数(上传文件的二进制数据、若上传多个文件时,多次使用该格式)
--本次文件上传的标识字符串\r\n
Content-Disposition: form-data; name="参数名"; filename="文件名"\r\n
Content-Type: 文件的MIMEType\r\n
\r\n
文件数据
\r\n
③添加结束标记,必须遵守格式
--本次文件上传的标识字符串--\r\n
示例程序:
#define XMGBoundary @"520it"
#define XMGEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]
#define XMGNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建请求
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 设置请求头(告诉告诉服务器,这是一个文件上传的请求)
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", XMGBoundary] forHTTPHeaderField:@"Content-Type"];
// 设置请求体
NSMutableData *body = [NSMutableData data];
// 文件参数
/*
--分割线\r\n
Content-Disposition: form-data; name="参数名"; filename="文件名"\r\n
Content-Type: 文件的MIMEType\r\n
\r\n
文件数据
\r\n
*/
// 分割线
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGNewLine];
// 文件参数名
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
[body appendData:XMGNewLine];
// 文件的类型
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
[body appendData:XMGNewLine];
// 文件数据
[body appendData:XMGNewLine];
// UIImageJPEGRepresentation(<#UIImage *image#>, <#CGFloat compressionQuality#>)
UIImage *image = [UIImage imageNamed:@"placeholder"];
[body appendData:UIImagePNGRepresentation(image)];
// [body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/test.png"]];
[body appendData:XMGNewLine];
// 非文件参数
/*
--分割线\r\n
Content-Disposition: form-data; name="参数名"\r\n
\r\n
参数值
\r\n
*/
// 分割线
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGNewLine];
// 参数名
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\""])];
[body appendData:XMGNewLine];
// 参数值
[body appendData:XMGNewLine];
[body appendData:XMGEncode(@"jack")];
[body appendData:XMGNewLine];
// 结束标记
/*
--分割线--\r\n
*/
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGEncode(@"--")];
[body appendData:XMGNewLine];
request.HTTPBody = body;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
}
@end
2、使用AFN提供的POST方法最便捷
①上传单个文件
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
[mgr POST:@"http://120.25.226.186:32812/upload" parameters:@{@"username" : @"123"}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// 在这个block中设置需要上传的文件
// NSData *data = [NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/placeholder.png"];
// [formData appendPartWithFileData:data name:@"file" fileName:@"test.png" mimeType:@"image/png"];
// [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/placeholder.png"] name:@"file" fileName:@"xxx.png" mimeType:@"image/png" error:nil];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/placeholder.png"] name:@"file" error:nil];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"-------%@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];
②上传多个文件文件
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);
}];
3、NSURLSessionConfiguration实现文件上传
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/upload"]];
request.HTTPMethod = @"POST";
// 设置请求头(告诉服务器,这是一个文件上传的请求)
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", XMGBoundary] forHTTPHeaderField:@"Content-Type"];
// 设置请求体
NSMutableData *body = [NSMutableData data];
// 文件参数
// 分割线
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGNewLine];
// 文件参数名
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
[body appendData:XMGNewLine];
// 文件的类型
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
[body appendData:XMGNewLine];
// 文件数据
[body appendData:XMGNewLine];
[body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/test.png"]];
[body appendData:XMGNewLine];
// 结束标记
/*
--分割线--\r\n
*/
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGEncode(@"--")];
[body appendData:XMGNewLine];
[[self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}] resume];
4、使用AFN的uploadTaskWithRequest方法需要类似NSURLSessionConfiguration、原始上传数据 拼接请求体比较麻烦
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
NSURLRequest *request = [NSURLRequest requestWithURL:@""];
NSMutableData *body = [NSMutableData data];
[mgr uploadTaskWithRequest:request fromData:body progress:<#(NSProgress *__autoreleasing *)#> completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
网友评论