用输入流NSInputStream 来实现图片,文件等的上传

场景

有时候,我们需要保存iPhone本地的资源(图片为例)到服务器的相应路径。那么就需要将本地图片上传到服务器。这样,可以用NSInputStream + NSURLConnection +NSMutableURLRequest来实现图片上传。

正文

开始我们需要在头文件.h中声明一些变量。如下:
NSURLConnection* _aSynConnection;
NSInputStream *_inputStreamForFile;
NSString *_localFilePath;

@property (nonatomic,retain) NSURLConnection* aSynConnection;
@property (nonatomic,retain) NSInputStream *inputStreamForFile;
@property (nonatomic,retain) NSString *localFilePath;
下面就是对上传图片的实际操作了。
开始的时候,我们需要将我们需要发送的数据,如图片等,转换为NSdata类型,然后通过类方法:inputStreamWithFileAtPath,来初始化我们刚才声明的inputStreamForFile。
然后,就是常规化的基于http协议的上传数据了。具体代码如下:
- (void)btnClickAction:(id)sender{
    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:request delegate:self];
    

}

这里是建立的异步请求,所以我们还需要实现协议方法。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse{
    returnInfoData=[[NSMutableData alloc]init];
    totalSize= [aResponse expectedContentLength];
    NSHTTPURLResponse * httpResponse;
    httpResponse = (NSHTTPURLResponse *)aResponse;
    if ((httpResponse.statusCode / 100) != 2) {
        NSLog(@"保存失败");
    } else {
        NSLog(@"保存成功");
    }
}

结束语

可能有人会问到,为什么我们要用输入流的方式上传文件呢。用NSdata,转换base64上传也可以啊。这里就有个效率问题了,我们用流的方式的话,数据是不进行任何,转换的,而其他方式是需要转换,所以,用流的方式,在同样的网速下,速度会更快些。

参考文章:http://blog.sina.com.cn/s/blog_7b9d64af01019qdr.html

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值