20 - 文件上傳、下載、解壓縮

小文件下載

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就不需要引入它)

  1. Unzipping
NSString *zipPath = @"path_to_your_zip_file";

NSString *destinationPath = @“path_to_the_folder_where_you_want_it_unzipped”;

[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];
  1. 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];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容