小文件下載
1.如果文件比較小,下載方式會(huì)比較多
直接用NSData的:
+ (id)dataWithContentsOfURL:(NSURL *)url;
- 但是
- 這種下載只使用于小文件
- 不足之處是無(wú)法暫停
NSURL *url= [NSURL URLWithString:@"http://123.123.123.32:324324/xxx.png"];
NSData *data = [NSData dataWithContentOfURL:url];
利用NSURLConnection發(fā)送一個(gè)HTTP請(qǐng)求去下載
如果是下載圖片,還可以利用SDWebImage框架
如果是大文件下載,建議使用NSURLSession或者第三方框架
文件上傳
文件上傳的步驟
// 設(shè)置請(qǐng)求頭
[request setValue:@"multipart/form-data; boundary=分割線" forHTTPHeaderField:@"Content-Type"];
// 設(shè)置請(qǐng)求體
// 非文件參數(shù)
-—分割線\r\n
Content-Disposition: form-data; name="參數(shù)名"\r\n
\r\n
參數(shù)值
\r\n
// 文件參數(shù)
--分割線\r\n
Content-Disposition: form-data; name="參數(shù)名"; filename="文件名"\r\n
Content-Type: 文件的MIMEType\r\n
\r\n
// 文件數(shù)據(jù)
\r\n
// 參數(shù)結(jié)束的標(biāo)記
--分割線--\r\n
部分文件的MIMEType

Snip20150903_13.png
獲得文件的MIMEType
// 利用NSURLConnection
- (NSString *)MIMEType:(NSURL *)url
{
// 1.創(chuàng)建一個(gè)請(qǐng)求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.發(fā)送請(qǐng)求(返回響應(yīng))
NSURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
// 3.獲得MIMEType
return response.MIMEType;
}
C語(yǔ)言API
+ (NSString *)mimeTypeForFileAtPath:(NSString *)path
{
if (![[NSFileManager alloc] init] fileExistsAtPath:path]) {
return nil;
}
}
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[path pathExtension], NULL);
CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
CFRelease(UTI);
if (!MIMEType) {
return @"application/octet-stream";
}
return NSMakeCollectable(MIMEType);
}
解壓縮
提供2個(gè)好用的第三方以及使用方法:
下載地址:https://github.com/samsoffes/ssziparchive
注意:需要引入libz.dylib框架(使用了CocoaPods就不需要引入它)
- Unzipping
NSString *zipPath = @"path_to_your_zip_file";
NSString *destinationPath = @“path_to_the_folder_where_you_want_it_unzipped”;
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];
- Zipping
NSString *zippedPath = @"path_where_you_want_the_file_created";
NSArray *inputPaths = [NSArray arrayWithObjects:
[[NSBundle mainBundle] pathForResource:@"photo1”ofType:@"jpg"],
[[NSBundle mainBundle] pathForResource:@"photo2" ofType:@"jpg"] nil];
[NSSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];