/// 文件上传
-
(void)NSURLSessionUploadTaskTest {
// 1.创建url 采用Apache本地服务器
NSString *urlString = @"http://localhost/upload/upload.php";
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:urlString];// 2.创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 文件上传使用post
request.HTTPMethod = @"POST";
NSString contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",@"boundary"];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
// 3.拼接表单,大小受MAX_FILE_SIZE限制(2MB) FilePath:要上传的本地文件路径 formName:表单控件名称,应于服务器一致
NSData data = [self getHttpBodyWithFilePath:@"/Users/userName/Desktop/IMG_0359.jpg" formName:@"file" reName:@"newName.png"];
request.HTTPBody = data;
// 根据需要是否提供,非必须,如果不提供,session会自动计算
[request setValue:[NSString stringWithFormat:@"%lu",data.length] forHTTPHeaderField:@"Content-Length"];// 4.1 使用dataTask
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSLog(@"upload success:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else {
NSLog(@"upload error:%@",error);
}}] resume];
if 0
// 4.2 开始上传 使用uploadTask fromData:可有可无,会被忽略
[[[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSLog(@"upload success:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else {
NSLog(@"upload error:%@",error);
}
}] resume];
endif
}
/// filePath:要上传的文件路径 formName:表单控件名称 reName:上传后文件名
-
(NSData *)getHttpBodyWithFilePath:(NSString *)filePath formName:(NSString *)formName reName:(NSString *)reName
{
NSMutableData *data = [NSMutableData data];
NSURLResponse *response = [self getLocalFileResponse:filePath];
// 文件类型:MIMEType 文件的大小:expectedContentLength 文件名字:suggestedFilename
NSString *fileType = response.MIMEType;// 如果没有传入上传后文件名称,采用本地文件名!
if (reName == nil) {
reName = response.suggestedFilename;
}// 表单拼接
NSMutableString *headerStrM =[NSMutableString string];
[headerStrM appendFormat:@"--%@\r\n",@"boundary"];
// name:表单控件名称 filename:上传文件名
[headerStrM appendFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n",formName,reName];
[headerStrM appendFormat:@"Content-Type: %@\r\n\r\n",fileType];
[data appendData:[headerStrM dataUsingEncoding:NSUTF8StringEncoding]];// 文件内容
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
[data appendData:fileData];NSMutableString *footerStrM = [NSMutableString stringWithFormat:@"\r\n--%@--\r\n",@"boundary"];
[data appendData:[footerStrM dataUsingEncoding:NSUTF8StringEncoding]];
// NSLog(@"dataStr=%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return data;
}
/// 获取响应,主要是文件类型和文件名 -
(NSURLResponse *)getLocalFileResponse:(NSString *)urlString
{
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
// 本地文件请求
NSURL *url = [NSURL fileURLWithPath:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];__block NSURLResponse *localResponse = nil;
// 使用信号量实现NSURLSession同步请求
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
localResponse = response;
dispatch_semaphore_signal(semaphore);
}] resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return localResponse;
}
网友评论