NSOutputStream-保存网络资源到本地

_filePath = [[NetworkManager sharedInstance] pathForTemporaryFileWithPrefix:@"Get"];

_fileStream = [NSOutputStream outputStreamToFileAtPath:self.filePath append:NO];

[_fileStream open];

 
 
2.进行网络请求,并返回网络的数据。
 
通过输出流对象,将数据写入到指定的文件中。
 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

NSInteger       dataLength;

const uint8_t * dataBytes;

NSInteger       bytesWritten;

NSInteger       bytesWrittenSoFar;

// 接收到的数据长度

dataLength = [data length];

dataBytes  = [data bytes];

bytesWrittenSoFar = 0;

do {

bytesWritten = [self.fileStream write:&dataBytes[bytesWrittenSoFar]maxLength:dataLength - bytesWrittenSoFar];

assert(bytesWritten != 0);

if (bytesWritten == -1) {

break;

} else {

bytesWrittenSoFar += bytesWritten;

}

} while (bytesWrittenSoFar != dataLength);

}

NSInputStream和NSMutableURLRequest-实现保存文件到服务器

1.准备工作,将需要的类进行声明定义。
*.h 文件

NSURLConnection* _aSynConnection;

NSInputStream *_inputStreamForFile;

NSString *_localFilePath;

 

@property (nonatomic,retain) NSURLConnection* aSynConnection;

@property (nonatomic,retain) NSInputStream *inputStreamForFile;

@property (nonatomic,retain) NSString *localFilePath;

 
*.m 文件

@synthesize inputStreamForFile=_inputStreamForFile;

@synthesize localFilePath=_localFilePath;

@synthesize aSynConnection=_aSynConnection;

 
2.进行请求
 

- (void)btnClickAction:(id)sender{

// 初始化目标地址的URL(发送到哪里)

NSURL *serverURL;

NSString *strURL=@"http://www.xxx.com/fileName.png";// 这里用图片为例

strURL = [strURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

serverURL=[NSURL URLWithString:strURL];

// 初始化本地文件路径,并与NSInputStream链接

self.localFilePath=@"本地的图片路径";

self.inputStreamForFile = [NSInputStream inputStreamWithFileAtPath:self.localFilePath];

// 上传大小

NSNumber *contentLength;

contentLength = (NSNumber *) [[[NSFileManager defaultManager]attributesOfItemAtPath:self.localFilePath error:NULL] objectForKey:NSFileSize];

NSMutableURLRequest *request;

request = [NSMutableURLRequest requestWithURL:serverURL];

[request setHTTPMethod:@"PUT"];

[request setHTTPBodyStream:self.inputStreamForFile];

[request setValue:@"image/png" forHTTPHeaderField:@"Content-Type"];

[request setValue:[contentLength description] forHTTPHeaderField:@"Content-Length"];

// 请求

self.aSynConnection = [NSURLConnection connectionWithRequest:requestdelegate:self];

}

 
3.接受回调函数的状态,判断是否上传成功。

// 收到响应时,会触发

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)aResponse{

NSLog(@"请求成功!");

returnInfoData=[[NSMutableData alloc]init];

totalSize= [aResponse expectedContentLength];

NSHTTPURLResponse * httpResponse;

httpResponse = (NSHTTPURLResponse *)aResponse;

if ((httpResponse.statusCode / 100) != 2) {

NSLog(@"保存失败");

} else {

NSLog(@"保存成功");

}

}

NSOutputStream\NSInputStream的更多相关文章

  1. NSStream

    NSStream 流是位数据通过通信路径的连续传送序列.它是单向的,从一个应用程序的角度,流可以是输入流(读操作流)或者输出流(写操作流),除了基于文件的流之外,其余的都是non-seekable的. ...

  2. ios开发网络学习五:输出流以及文件上传

    一:输出流 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelega ...

  3. iOS开发——网络篇——文件下载(NSMutableData、NSFileHandle、NSOutputStream)和上传、压缩和解压(三方框架ZipArchive),请求头和请求体格式,断点续传Range

    一.小文件下载 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion ...

  4. Cocoa Touch(二):数据存储CoreData, NSKeyArchiver, NSOutputStream, NSUserDefaults

    应用程序离不开数据的永久存储,有两种方式实现存储:数据库和文本文件. 作为存储管理器,最基本的功能就是增删改查了. CoreData 1.插入 AppDelegate *app = [[UIAppli ...

  5. iOS开发系列-NSOutputStream

    NSOutputStream 创建一个NSOutputStream实例 - (nullable instancetype)initToFileAtPath:(NSString *)path appen ...

  6. 【原】AFNetworking源码阅读(五)

    [原]AFNetworking源码阅读(五) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇中提及到了Multipart Request的构建方法- [AFHTTP ...

  7. AFNetworking 3.0 源码解读 总结(干货)(下)

    承接上一篇AFNetworking 3.0 源码解读 总结(干货)(上) 21.网络服务类型NSURLRequestNetworkServiceType 示例代码: typedef NS_ENUM(N ...

  8. AFNetworking 3.0 源码解读(三)之 AFURLRequestSerialization

    这篇就讲到了跟请求相关的类了 关于AFNetworking 3.0 源码解读 的文章篇幅都会很长,因为不仅仅要把代码进行详细的的解释,还会大概讲解和代码相关的知识点. 上半篇: URI编码的知识 关于 ...

  9. iOS---后台运行机制详解

    一.iOS的“伪后台”程序 首先,先了解一下iOS 中所谓的「后台进程」到底是怎么回事吧? Let me be as clear as I can be: the iOS multitasking b ...

随机推荐

  1. jquery之隐藏div

    1.$("#demo").attr("style","display:none;");//隐藏div $("#demo" ...

  2. DHCP服务器

    DHCP指的是由服务器控制一段IP地址范围,客户机登录服务器时就可以自动获得服务器分配的IP地址和子网掩码.首先,DHCP服务器必须是一台安装有Windows 2000 Server/Advanced ...

  3. 报错:ORA-02287: 此处不允许序号

    CREATE TABLE MY_TAB (N1 NUMBER(5),N2 DATE);          SELECT  * FROM MY_TAB;          CREATE SEQUENCE ...

  4. [!] CocoaPods was not able to update the `master` repo...

    输入pod install之后出现: [!] CocoaPods was not able to update the `master` repo. If this is an unexpected ...

  5. JavaScript--模拟网络爬虫

    <!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...

  6. 数据类型的转换String

    x.toString(): 无法转换null和undefined 不过String()却是万能的,其中的原理如下 function String(x){ if(x===undefined){ retu ...

  7. Java简介(4)-关键字

    abstract assert boolean break byte byte case catch char class const continue default do-while double ...

  8. java获得url里面所带参数的值

    url: http://localhost:8080/test/list?p=1&d=2014 要获得所带参数p和d的值,方法如下: int p = Integer.parseInt(requ ...

  9. angularJS内置指令一览

    基础ng指令 ng-href ng-src ng-disabled ng-readonly ng-checked ng-selected ng-class ng-style ng-show ng-hi ...

  10. jquery hide() show()

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...