zoukankan      html  css  js  c++  java
  • (一二九)获取文件的MineType、利用SSZipArchive进行压缩解压

    MineType

    简介

    文件在网络上以二进制流的方式传播,为了区分不同的文件类型,用MineType来标明。

    为什么要获取

    文件的拓展名较短,比较好记,但是MineType是很长的,比如docx拓展名的MineType是application/vnd.openxmlformats-officedocument.wordprocessingml.document,因此比较合适的方案是根据拓展名直接得到MineType。

    怎么做

    比较幸运,通过URLConnection的响应体response就能拿到MineType,我们只需要把获取本地文件包装成一个URL请求,然后拿到response即可,代码如下:

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"docx"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@",response.MIMEType);
    }];

    文件的压缩与解压

    第三方框架

    SSZipArchive是一个用于ZIP压缩与解压的第三方框架,可作为工具类使用,十分方便。

    导入

    下载完毕后,将minizip文件夹与SSZipArchive类文件导入工程,并且添加动态库libz.dylib(在Build Phases的Link Binary With Libraries中添加)。

    使用

    通过类方法createZipFileAtPath:withFilesAtPaths:和unzipFileAtPath:toDestination:分别可以实现压缩和解压。假设现在工程中有4_7inch1.jpg~4_7inch4.jpg四个文件,下面的代码在触摸开始时对他们进行压缩,并保存在沙盒的Library/Caches中;在触摸结束时将其解压。

    • 注意解压时应该指定一个目录,否则会在当前目录解压所有文件。
    • 通过类方法的返回值可以判断操作是否成功。

    代码如下:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        NSMutableArray *paths = [NSMutableArray array];
        for (int i = 1; i <= 4; i++) {
            NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"4_7inch%d.jpg",i] ofType:nil];
            [paths addObject:path];
        }
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *outPath = [cachePath stringByAppendingPathComponent:@"imgs.zip"];
        if([SSZipArchive createZipFileAtPath:outPath withFilesAtPaths:paths]){
            NSLog(@"success");
        } 
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *zipPath = [cachePath stringByAppendingPathComponent:@"imgs.zip"];
        if ([SSZipArchive unzipFileAtPath:zipPath toDestination:[cachePath stringByAppendingPathComponent:@"imgs/"]]) {
            NSLog(@"success");
        }  
    }
  • 相关阅读:
    .NET MVC后台发送post请求
    (整理)Sublime Text 3 安装、破解、安装Package Control、汉化、添加到右键菜单、代码格式化、禁止更新
    百度api查询多个地址的经纬度的问题
    try{}里有一个 return 语句,那么紧跟在这个 try 后的 finally {}里的 code 会 不会被执行,什么时候被执行,在 return 前还是后?
    js获取某个日期所在周周一的日期
    重学C++ (1)
    基于.NET平台常用的框架整理
    指针常量和常量指针的区别
    C++四种强制类型转换关键字
    const define 定义常量的区别
  • 原文地址:https://www.cnblogs.com/aiwz/p/6154025.html
Copyright © 2011-2022 走看看