美文网首页
网络请求之文件下载、文件上传、解压缩

网络请求之文件下载、文件上传、解压缩

作者: WenJim | 来源:发表于2017-11-24 15:37 被阅读22次

小文件下载

  • 如果文件比较小,下载方式会比较多

    • 直接用NSData的+ (id)dataWithContentsOfURL:(NSURL *)url;
    • 利用NSURLConnection发送一个HTTP请求去下载
    • 如果是下载图片,还可以利用SDWebImage框架
  • 如果是大文件下载,建议使用NSURLSession或者第三方框架

具体代码操作如下:

-(void)download
{
    // 下载文件
    NSURL * fileURL = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_05.mp4"];
    
    // 2. 创建请求对象
    NSURLRequest * request = [NSURLRequest requestWithURL:fileURL];
    
    // 3. 发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
    
    
            // 4. 写数据到沙盒中
            NSString * fileStr =  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
            NSString * fullPath =  [fileStr stringByAppendingPathComponent:@"123.mp4"];
    
            NSLog(@"保存位置:%@",fullPath);
    
            [data writeToFile:fullPath atomically:YES];
    
    
            NSLog(@"完成");
            
        }];
}
  • 第二种方式小文件下载
-(void)download4
{
    // 下载文件
    NSURL * fileURL = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_05.mp4"];
    
    // 2. 创建请求对象
    NSURLRequest * request = [NSURLRequest requestWithURL:fileURL];
    
    // 3. 发送请求
//    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [NSURLConnection connectionWithRequest:request delegate:self];

}

#pragma mark - NSURLConnectionDelegate
// 1. 当接收到服务器响应的时候调用
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%s",__func__);
    // 得到文件的总大小(本次请求的文件数据的总大小)
    self.totalSize = response.expectedContentLength;
    
}

// 2. 接收到服务器返回数据的时候调用,调用多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
//    NSLog(@"%zd",data.length);
    [self.fileData appendData:data];
    
    // 进度 = 已经下载 / 文件总大小
    NSLog(@"%f",1.0 * self.fileData.length / self.totalSize);
}

// 3. 当请求失败的时候会调用
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//    NSLog(@"%s",__func__);
    NSLog(@"%@",error);
}

// 4. 请求结束的时候调用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%s",__func__);
    // 4. 写数据到沙盒中
    NSString * fileStr =  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString * fullPath =  [fileStr stringByAppendingPathComponent:@"123.mp4"];
    
    [self.fileData writeToFile:fullPath atomically:YES];
    
    NSLog(@"保存位置:%@",fullPath);

}

文件上传的步骤

  • 设置请求头
    [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

具体代码如下:

-(void)upload
{
    // 1. 确定请求路径
    NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
    
    // 2. 创建请求对象
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    
    // 3. 设置请求方法
    request.HTTPMethod = @"POST";
    
    // 4. 设置请求头信息
    // Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryQPb2PB0tzJZMkCLa
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary] forHTTPHeaderField:@"Content-Type"];
    
    // 5. 拼接请求体数据
    NSMutableData * filedata = [NSMutableData data];
    // 5.1 文件参数
    /*
     --分隔符
     Content-Disposition: form-data; name="file"; filename="静态05.jpg"
     Content-Type: image/jpeg(MIMEType:大类型/小类型)
     空行
     文件参数
     */
    
    NSData * oneData = [[NSString stringWithFormat:@"--%@",Kboundary] dataUsingEncoding:NSUTF8StringEncoding];
    
    [filedata appendData:oneData];
    // 把换行添加进请求体数据中
    [filedata appendData:KNewLine];
    // name:file 服务器规定的参数
    // filename: 静态05.jpg 文件保存到服务器上面的名称
    // Content-Type: 文件的类型
    NSData * twoData = [@"Content-Disposition: form-data; name=\"file\"; filename=\"静态05.jpg\"" dataUsingEncoding:NSUTF8StringEncoding];
    
    [filedata appendData:twoData];
    [filedata appendData:KNewLine];
    
    NSData * thirdlyData = [@"Content-Type: image/jpeg" dataUsingEncoding:NSUTF8StringEncoding];
    [filedata appendData:thirdlyData];
    [filedata appendData:KNewLine];
    [filedata appendData:KNewLine];
    
    UIImage * image = [UIImage imageNamed:@"静态05"];
    // UIImage --> NSData
    NSData * imageData = UIImageJPEGRepresentation(image, 0.5);
    [filedata appendData:imageData];
    [filedata appendData:KNewLine];
    
    // 5.2 非文件参数
    /*
     --分隔符
     Content-Disposition: form-data; name="username"
     空行
     456123
     */
    NSData * sixthData = [[NSString stringWithFormat:@"--%@",Kboundary] dataUsingEncoding:NSUTF8StringEncoding];
    
    [filedata appendData:sixthData];
    [filedata appendData:KNewLine];
    
    NSData * seventhData = [@"Content-Disposition: form-data; name=\"username\"" dataUsingEncoding:NSUTF8StringEncoding];
    [filedata appendData:seventhData];
    [filedata appendData:KNewLine];
    [filedata appendData:KNewLine];
    
    NSData * ninthData = [@"456123" dataUsingEncoding:NSUTF8StringEncoding];
    [filedata appendData:ninthData];
    [filedata appendData:KNewLine];
    
    
    // 5.3 结尾标识
    NSData * tenthData = [[NSString stringWithFormat:@"--%@--",Kboundary] dataUsingEncoding:NSUTF8StringEncoding];
    
    [filedata appendData:tenthData];
    
    
    // 6. 设置请求体
    request.HTTPBody = filedata;
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        // 8. 解析数据
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        
    }];
    
}

部分文件的MIMEType

类型 文件扩展名 MIMEType
png image/png
bmp\dib image/ bmp
jpe\jpeg\jpg image/jpeg
gif image/gif
mp3 audio/mpeg
多媒体 mp4\mpg4\m4vmp4v video/mp4
js application/javascript
pdf application/pdf
文本 text\txt text/plain
json application/json
xml text/xml

获得文件的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, (__bridge CFStringRef)[path pathExtension], NULL);
    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    if (!MIMEType) {
        return @"application/octet-stream";
    }
    return (__bridge NSString *)(MIMEType);
}

压缩(使用第三方框架--ZipArchive )

下载地址:https://github.com/ZipArchive/ZipArchive

  • 需要引入libz.dylib框架
  • 导入头文件Main.h
  • 创建压缩文件
+ (BOOL)createZipFileAtPath:(NSString *)path
           withFilesAtPaths:(NSArray *)paths;
+ (BOOL)createZipFileAtPath:(NSString *)path
    withContentsOfDirectory:(NSString *)directoryPath;
  • 解压
+ (BOOL)unzipFileAtPath:(NSString *)path
          toDestination:(NSString *)destination

相关文章

网友评论

      本文标题:网络请求之文件下载、文件上传、解压缩

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