场景
有时候,我们需要保存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