美文网首页
20 - 文件上传、下载、解压缩

20 - 文件上传、下载、解压缩

作者: RadioWaves | 来源:发表于2017-07-02 17:09 被阅读8次

    小文件下载

    1.如果文件比较小,下载方式会比较多
    直接用NSData的:
    + (id)dataWithContentsOfURL:(NSURL *)url;

    • 但是
    • 这种下载只使用于小文件
    • 不足之处是无法暂停
    NSURL *url= [NSURL URLWithString:@"http://123.123.123.32:324324/xxx.png"];
    NSData *data = [NSData dataWithContentOfURL:url];
    

    利用NSURLConnection发送一个HTTP请求去下载
    如果是下载图片,还可以利用SDWebImage框架

    如果是大文件下载,建议使用NSURLSession或者第三方框架


    文件上传

    文件上传的步骤
    // 设置请求头
    [request setValue:@"multipart/form-data; boundary=分割线" forHTTPHeaderField:@"Content-Type"];
    
    // 设置请求体
    // 非文件参数
    -—分割线\r\n
    Content-Disposition: form-data; name="参数名"\r\n
    \r\n
    参数值
    \r\n
    
    // 文件参数
    --分割线\r\n
    Content-Disposition: form-data; name="参数名"; filename="文件名"\r\n
    Content-Type: 文件的MIMEType\r\n
    
    \r\n
    // 文件数据
    \r\n
    
    // 参数结束的标记
    --分割线--\r\n
    

    部分文件的MIMEType

    Snip20150903_13.png

    获得文件的MIMEType

    // 利用NSURLConnection
    - (NSString *)MIMEType:(NSURL *)url
    {
        // 1.创建一个请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
        // 2.发送请求(返回响应)
        NSURLResponse *response = nil;
        [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
        // 3.获得MIMEType
        return response.MIMEType;
    }
    

    C语言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个好用的第三方以及使用方法:
    下载地址: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];
    

    相关文章

      网友评论

          本文标题:20 - 文件上传、下载、解压缩

          本文链接:https://www.haomeiwen.com/subject/byxocxtx.html