iOS学习笔记(二十八)————文件的上传与下载

/ 0评 / 0

来看一下文件的上传与下载,我们先用 php 写一个简单的文件上传服务器,看一下代码

	$content = file_get_contents("php://input");

	$imgName = time();
	$file_dir='images/'.$imgName.".jpg";

	if($fp = fopen($file_dir,'w')){
		if(fwrite($fp,$content)){
			fclose($fp);
			echo "上传成功";
		}
	}

由于之前说过以前的 NSUrlConnection 将要被放弃了,所以我们演示只用 NSUrlSession,来看一下图片的上传

- (void)uploadImageTest{
	    NSURLSession *session = [NSURLSession sharedSession];
	    
	    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/upload/index.php"]];
	     [request addValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
	     [request addValue:@"text/html" forHTTPHeaderField:@"Accept"];
	     [request setHTTPMethod:@"POST"];
	     [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
	     [request setTimeoutInterval:20];
	    
	     NSData * imagedata = UIImageJPEGRepresentation([UIImage imageNamed:@"0.jpg"],1);
	     //当然这里我们也可以是你用 base64 编码一下。


	     NSURLSessionUploadTask * uploadtask = [session uploadTaskWithRequest:request fromData:imagedata completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
	         NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
	     }];
	    [uploadtask resume];
}

再来看一下文件的下载,基本的下载 是把数据都保存在_buffer中,_buffer是运行时内存中的一个对象,如果需要下载的数据量很大,内存会不够用,所以只能用于小文件的下载,大文件下载:边下边存,每次从服务器请求一段数据之后,就写入到沙盒中
小文件的下载:

- (void)downloadSmallTest{
    // 下面这个方法是同步的
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://localhost/upload/images/1467621024.jpg"]];
    [data writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/c.jpg"] atomically:YES];
    
    

    NSString *str = @"http://localhost/upload/images/1467621024.jpg";
    // 如果请求地址中有中文 需要编码
    //str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:str] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        [data writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/d.jpg"] atomically:YES];
        NSLog(@"%@",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/d.jpg"]);
        
    }];
    [downloadTask resume];
}

大文件的下载(这里简单的用到了断点续传)

- (NSURLSession *)session{
    if (!_session) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}

//开始按钮
- (IBAction)start:(UIButton *)sender {
    if (self.resumeData) {
        [self resume];
    }else{
        [self start1];
    }
}

//暂停按钮
- (IBAction)stop:(id)sender {
    [self pause];
}


- (void)start1{
    //创建下载任务
    NSString *str = @"http://localhost/upload/zookeeper.zip";
    NSURL *url = [NSURL URLWithString:str];
    self.task = [self.session downloadTaskWithURL:url];
    //开始下载任务
    [self.task resume];
}

- (void)pause{
    //暂停下载任务
    __weak typeof(self) vc = self;
    [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        vc.resumeData = resumeData;
        vc.task = nil;
        NSLog(@"%@",resumeData);
    }];
}

- (void)resume{
    //继续下载任务
    if(!self.resumeData){
        NSString *str = @"http://localhost/upload/zookeeper.zip";
        NSURL *url = [NSURL URLWithString:str];
        self.task = [self.session downloadTaskWithURL:url];
    }else{
        self.task=[_session downloadTaskWithResumeData:self.resumeData];
    }
    [self.task resume];
    self.resumeData=nil;
}


#pragma mark delegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
    
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    //拿到Doc路径
    NSString *path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES )  lastObject];
    //存储文件夹及文件名
    NSString *pathUrl = [path stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    NSFileManager *manager = [NSFileManager defaultManager];
    //移动文件
    [manager moveItemAtPath:location.path toPath:pathUrl error:nil];
    
    NSLog(@"%@",pathUrl);
    
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    self.progress.progress = (double)totalBytesWritten/totalBytesExpectedToWrite;
    NSLog(@"已下载%f",(double)totalBytesWritten/totalBytesExpectedToWrite);
}

//这个方法没有使用
- (NSString *)getFilePath{
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    // 文件夹的路径
    NSString *directoryPath = [NSString stringWithFormat:@"%@/Files",path];
    
    // 判断文件夹是否存在,如果不存在就创建一个文件夹
    if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath]){
        [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    // 文件路径
    NSString *filePath = [NSString stringWithFormat:@"%@/a.zip",directoryPath];
    
    // 判断文件夹中的文件是否存在,如果不存在 也要创建一个空的文件
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    }
    
    return filePath;
}

代码请查看 http://git.oschina.net/zcb1603999/LearningiOS

评论已关闭。