码迷,mamicode.com
首页 > 移动开发 > 详细

IOS 上传下载

时间:2017-05-30 16:23:06      阅读:350      评论:0      收藏:0      [点我收藏+]

标签:ide   同步方法   gcd   array   tle   dom   test   datawit   字典   

技术分享

技术分享

技术分享

技术分享

    技术分享

 

 

下载地址:https://github.com/samsoffes/ssziparchive
注意:需要引入libz.dylib框架 
// Unzipping
NSString *zipPath = @"path_to_your_zip_file";
NSString *destinationPath = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];

// 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];
[SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];

 

技术分享

Content-Type multipart/form-data; boundary=本次上传标示字符串(不能中文)

--本次上传标示字符串 \n
Content-Disposition: form-data; name="服务端字段"; filename="上传文件名" \n
Content-Type: 上传文件MIMEType \n\n

要上传的二进制数据

--本次上传标示字符串 \n
Content-Disposition: form-data; name="submit" \n\n

Submit \n
--本次上传标示字符串-- \n

 

 

 

 技术分享

类型

文件拓展名

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

 

 

            post上传

技术分享
//
//  UploadFile.m
//  02.Post上传


#import "UploadFile.h"

@implementation UploadFile
// 拼接字符串
static NSString *boundaryStr = @"--";   // 分隔字符串
static NSString *randomIDStr;           // 本次上传标示字符串
static NSString *uploadID;              // 上传(php)脚本中,接收文件字段

- (instancetype)init
{
    self = [super init];
    if (self) {
        randomIDStr = @"itcast";
        uploadID = @"uploadFile";
    }
    return self;
}

#pragma mark - 私有方法
- (NSString *)topStringWithMimeType:(NSString *)mimeType uploadFile:(NSString *)uploadFile
{
    NSMutableString *strM = [NSMutableString string];
    
    [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
    [strM appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\n", uploadID, uploadFile];
    [strM appendFormat:@"Content-Type: %@\n\n", mimeType];
    
    NSLog(@"%@", strM);
    return [strM copy];
}

- (NSString *)bottomString
{
    NSMutableString *strM = [NSMutableString string];
    
    [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
    [strM appendString:@"Content-Disposition: form-data; name=\"submit\"\n\n"];
    [strM appendString:@"Submit\n"];
    [strM appendFormat:@"%@%@--\n", boundaryStr, randomIDStr];
    
    NSLog(@"%@", strM);
    return [strM copy];
}

#pragma mark - 上传文件
- (void)uploadFileWithURL:(NSURL *)url data:(NSData *)data
{
    // 1> 数据体
    NSString *topStr = [self topStringWithMimeType:@"image/png" uploadFile:@"头像1.png"];
    NSString *bottomStr = [self bottomString];
    
    NSMutableData *dataM = [NSMutableData data];
    [dataM appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]];
    [dataM appendData:data];
    [dataM appendData:[bottomStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    // 1. Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f];
    
    // dataM出了作用域就会被释放,因此不用copy
    request.HTTPBody = dataM;
    
    // 2> 设置Request的头属性
    request.HTTPMethod = @"POST";
    
    // 3> 设置Content-Length
    NSString *strLength = [NSString stringWithFormat:@"%ld", (long)dataM.length];
    [request setValue:strLength forHTTPHeaderField:@"Content-Length"];
    
    // 4> 设置Content-Type
    NSString *strContentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", randomIDStr];
    [request setValue:strContentType forHTTPHeaderField:@"Content-Type"];
    
    // 3> 连接服务器发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", result);
    }];
}



@end
View Code
技术分享
//
//  MJViewController.m
//  02.Post上传


#import "MJViewController.h"
#import "UploadFile.h"

@interface MJViewController ()

@end

@implementation MJViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UploadFile *upload = [[UploadFile alloc] init];
    
    NSString *urlString = @"http://localhost/upload.php";
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"头像1.png" ofType:nil];
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    [upload uploadFileWithURL:[NSURL URLWithString:urlString] data:data];
}

@end
View Code

 

文件下载

技术分享
//
//  FileDownload.m
//  01.文件下载
//


#import "FileDownload.h"
#import "NSString+Password.h"

#define kTimeOut        2.0f
// 每次下载的字节数
#define kBytesPerTimes  20250

@interface FileDownload()
@property (nonatomic, strong) NSString *cacheFile;
@property (nonatomic, strong) UIImage *cacheImage;
@end

@implementation FileDownload
/**
 为了保证开发的简单,所有方法都不使用多线程,所有的注意力都保持在文件下载上
 
 在开发中如果碰到比较绕的计算问题时,建议:
 1> 测试数据不要太大
 2> 测试数据的数值变化,能够用笔算计算出准确的数值
 3> 编写代码对照测试

 */
//- (NSString *)cacheFile
//{
//    if (!_cacheFile) {
//        NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//        _cacheFile = [cacheDir stringByAppendingPathComponent:@"123.png"];
//    }
//    return _cacheFile;
//}
- (UIImage *)cacheImage
{
    if (!_cacheImage) {
        _cacheImage = [UIImage imageWithContentsOfFile:self.cacheFile];
    }
    return _cacheImage;
}

- (void)setCacheFile:(NSString *)urlStr
{
    NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    urlStr = [urlStr MD5];
    
    _cacheFile = [cacheDir stringByAppendingPathComponent:urlStr];
}

- (void)downloadFileWithURL:(NSURL *)url completion:(void (^)(UIImage *image))completion
{
    // GCD中的串行队列异步方法
    dispatch_queue_t q = dispatch_queue_create("cn.itcast.download", DISPATCH_QUEUE_SERIAL);
    
    dispatch_async(q, ^{
        NSLog(@"%@", [NSThread currentThread]);
        
        // 把对URL进行MD5加密之后的结果当成文件名
        self.cacheFile = [url absoluteString];
        
        // 1. 从网络下载文件,需要知道这个文件的大小
        long long fileSize = [self fileSizeWithURL:url];
        // 计算本地缓存文件大小
        long long cacheFileSize = [self localFileSize];
        
        if (cacheFileSize == fileSize) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(self.cacheImage);
            });
            NSLog(@"文件已经存在");
            return;
        }
        
        // 2. 确定每个数据包的大小
        long long fromB = 0;
        long long toB = 0;
        // 计算起始和结束的字节数
        while (fileSize > kBytesPerTimes) {
            // 20480 + 20480
            //
            toB = fromB + kBytesPerTimes - 1;
            
            // 3. 分段下载文件
            [self downloadDataWithURL:url fromB:fromB toB:toB];
            
            fileSize -= kBytesPerTimes;
            fromB += kBytesPerTimes;
        }
        [self downloadDataWithURL:url fromB:fromB toB:fromB + fileSize - 1];

        dispatch_async(dispatch_get_main_queue(), ^{
            completion(self.cacheImage);
        });        
    });
}

#pragma mark 下载指定字节范围的数据包
/**
 NSURLRequestUseProtocolCachePolicy = 0,        // 默认的缓存策略,内存缓存
 
 NSURLRequestReloadIgnoringLocalCacheData = 1,  // 忽略本地的内存缓存
 NSURLRequestReloadIgnoringCacheData
 */
- (void)downloadDataWithURL:(NSURL *)url fromB:(long long)fromB toB:(long long)toB
{
    NSLog(@"数据包:%@", [NSThread currentThread]);
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:kTimeOut];
    
    // 指定请求中所要GET的字节范围
    NSString *range = [NSString stringWithFormat:@"Bytes=%lld-%lld", fromB, toB];
    [request setValue:range forHTTPHeaderField:@"Range"];
    NSLog(@"%@", range);
    
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
    
    // 写入文件,覆盖文件不会追加
//    [data writeToFile:@"/Users/aplle/Desktop/1.png" atomically:YES];
    [self appendData:data];
    
    NSLog(@"%@", response);
}

#pragma mark - 读取本地缓存文件大小
- (long long)localFileSize
{
    // 读取本地文件信息
    NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:self.cacheFile error:NULL];
    NSLog(@"%lld", [dict[NSFileSize] longLongValue]);
    
    return [dict[NSFileSize] longLongValue];
}

#pragma mark - 追加数据到文件
- (void)appendData:(NSData *)data
{
    // 判断文件是否存在
    NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:self.cacheFile];
    // 如果文件不存在创建文件
    if (!fp) {
        [data writeToFile:self.cacheFile atomically:YES];
    } else {
        // 如果文件已经存在追加文件
        // 1> 移动到文件末尾
        [fp seekToEndOfFile];
        // 2> 追加数据
        [fp writeData:data];
        // 3> 写入文件
        [fp closeFile];
    }
}

#pragma mark - 获取网络文件大小
- (long long)fileSizeWithURL:(NSURL *)url
{
    // 默认是GET
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeOut];
    
    // HEAD 头,只是返回文件资源的信息,不返回具体是数据
    // 如果要获取资源的MIMEType,也必须用HEAD,否则,数据会被重复下载两次
    request.HTTPMethod = @"HEAD";

    // 使用同步方法获取文件大小
    NSURLResponse *response = nil;
    
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
    
    // expectedContentLength文件在网络上的大小
    NSLog(@"%lld", response.expectedContentLength);
    
    return response.expectedContentLength;
}

@end
View Code
技术分享
//
//  MJViewController.m
//  01.文件下载
//
//  Created by apple on 14-4-29.
//  Copyright (c) 2014年 itcast. All rights reserved.
//

#import "MJViewController.h"
#import "FileDownload.h"

@interface MJViewController ()
@property (nonatomic, strong) FileDownload *download;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end

@implementation MJViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.download = [[FileDownload alloc] init];
    [self.download downloadFileWithURL:[NSURL URLWithString:@"http://localhost/itcast/images/head4.png"] completion:^(UIImage *image) {
        
        self.imageView.image = image;
    }];
}

@end
View Code

 

Post Json解析数据

技术分享
//
//  MJViewController.m
//  03.Post JSON
//


#import "MJViewController.h"
#import "Person.h"

@interface MJViewController ()

@end

@implementation MJViewController
/**
 序列化:   将字典或数组变成顺序(序列的)二进制数据流,以便于网络传输
 反序列化:  将从网络接收到的二进制数据流,转换成数据和字典的过程
 */
- (void)viewDidLoad
{
    [super viewDidLoad];

    [self postObj];
}

- (void)postObj
{
    // 1. URL
    NSURL *url = [NSURL URLWithString:@"http://localhost/postjson.php"];
    
    // 2. Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f];
    request.HTTPMethod = @"POST";
    
    Person *p = [[Person alloc] init];
    p.name = @"zhang";
    p.age = 19;

    // KVC给对象赋值
//    p setValuesForKeysWithDictionary:<#(NSDictionary *)#>
    // 使用KVC把对象变成字典
    // 需要指定对象的属性的键值数组
    // 数组中指定的键值,必须是对象的属性
    // 错误示例1
//    id obj = [p dictionaryWithValuesForKeys:@[@"name", @"age1"]];
    // 键值数组中,不一定要包含全部的属性
    id obj = [p dictionaryWithValuesForKeys:@[@"name"]];
//    id obj = [p dictionaryWithValuesForKeys:@[@"name", @"age"]];
    
    // 提示dataWithJSONObject只能对NSDictionary和NSArray进行序列化
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:obj options:0 error:NULL];
    
    // 3. Connection
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSLog(@"%@", result);
    }];
}

- (void)postJSON
{
    // 1. URL
    NSURL *url = [NSURL URLWithString:@"http://localhost/postjson.php"];
    
    // 2. Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f];
    request.HTTPMethod = @"POST";
    
    // 在iOS中JSON就是Dict/Array
    // 使用NSDictionary & NSArray可以各种灵活组合
    NSDictionary *dict = @{
                           @"name": @"zhangsan",
                           @"age" : @18,
                           @"book" : @[
                                   @"iOS 1",
                                   @"iOS 2"
                                   ],
                           @"zoom" : @1
                           };
    NSDictionary *dict1 = @{
                           @"name": @"lisi",
                           @"age" : @24,
                           @"book" : @[
                                   @"iOS 7",
                                   @"iOS 6"
                                   ],
                           @"zoom" : @2
                           };
    NSArray *array = @[dict, dict1];
    
    // 把字典转换成二进制数据流, 序列化
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
    
    // 将data转换成NSDictionary 反序列化
//    [NSJSONSerialization JSONObjectWithData:<#(NSData *)#> options:<#(NSJSONReadingOptions)#> error:<#(NSError *__autoreleasing *)#>]
    
    // 3. Connection
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
       
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSLog(@"%@", result);
    }];
    
}

@end
View Code

 

 

URLSessin文件上传

 

技术分享
//
//  MJViewController.m
//  04.URLSessin Upload
//


#import "MJViewController.h"

@interface MJViewController ()

@end

@implementation MJViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self uploadFile];
}

#pragma mark - 用Session上传头像
- (void)uploadFile
{
    // 1. NSURL
    NSString *urlString = @"http://localhost/uploads/测试一下.png";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
//    NSURL *url = [NSURL URLWithString:@"http://localhost/uploads/测试一下.png"];
    
    // 2. Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0];
    
    request.HTTPMethod = @"PUT";
    
    // 设置用户授权
    // 1> "admin:123456"
    NSString *authStr = @"admin:123456";
    // 2> result = 对字符串进行BASE64编码(网络传输中常用的一种编码格式,NSData)
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *result = [authData base64EncodedStringWithOptions:0];
    // 3> "Basic result" => 提交给服务器的验证字符串,用来验证身份
    NSString *authString = [NSString stringWithFormat:@"Basic %@", result];
    
    // 设置HTTP请求头的数值,设置用户授权
    [request setValue:authString forHTTPHeaderField:@"Authorization"];
    
    // 3. Session,有一个单例,是全局共享的
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 4. 文件上传
    NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];
    // 所有任务默认都是挂起的
    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:bundleURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        // 上传完成操作
        NSLog(@"%@", response);
    }];
    
    [task resume];
}

@end
View Code

 

 

 

 

 

IOS 上传下载

标签:ide   同步方法   gcd   array   tle   dom   test   datawit   字典   

原文地址:http://www.cnblogs.com/liuwj/p/6920157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!