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");
        }  
    }
  • 相关阅读:
    Web进程被kill掉后线程还在运行怎么办?
    Spring Boot学习(二):配置文件
    POI实现excel的数据验证
    Spring Boot学习(一):入门篇
    lombok学习
    Java设计模式:单例模式
    关于org.springframework.web.filter.CharacterEncodingFilter的学习
    毕业三年,拿了北京户口,从年薪20W到年薪40W,说一点对后人有用的经验
    北漂去帝都大医院求医到底有多难?我的真实经历,真的是一路坎坷与辛酸~
    阿里面试官让我讲讲Unicode,我讲了3秒说没了,面试官说你可真菜
  • 原文地址:https://www.cnblogs.com/aiwz/p/6154025.html
Copyright © 2011-2022 走看看