原文:NSInputStream和NSMutableURLRequest-实现保存文件到服务器_贞娃儿_新浪博客
有时候,我们需要保存iPhone本地的资源(图片为例)到服务器的相应路径。那么就需要将本地图片上传到服务器。这样,可以用NSInputStream+NSURLConnection+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 文件
@synthesizeinputStreamForFile=_inputStreamForFile;
@synthesizelocalFilePath=_localFilePath;
@synthesizeaSynConnection=_aSynConnection;
2.进行请求
实现同步、异步请求
//我将其写入按钮事件中
-(void)btnClickAction:(id)sender{
NSLog(@"--------btnClickAction--------");
//初始化目标地址的URL(发送到哪里)
NSURL*serverURL;
NSString*strURL=@"http://www.xxx.com/fileName.png";//这里用图片为例
strURL = [strURLstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
serverURL=[NSURLURLWithString:strURL];
//初始化本地文件路径,并与NSInputStream链接
self.localFilePath=@"本地的图片路径";
self.inputStreamForFile= [NSInputStreaminputStreamWithFileAtPath:self.localFilePath];
//上传大小
NSNumber*contentLength;
contentLength = (NSNumber*)
[[[NSFileManagerdefaultManager]attributesOfItemAtPath:self.localFilePatherror:NULL]objectForKey:NSFileSize];
NSMutableURLRequest*request;
request = [NSMutableURLRequestrequestWithURL:serverURL];
[requestsetHTTPMethod:@"PUT"];
[requestsetHTTPBodyStream:self.inputStreamForFile];
[requestsetValue:@"image/png"forHTTPHeaderField:@"Content-Type"];
[requestsetValue:[contentLengthdescription]forHTTPHeaderField:@"Content-Length"];
//请求
self.aSynConnection= [NSURLConnectionconnectionWithRequest:requestdelegate:self];
}
3.接受回调函数的状态,判断是否上传成功。
//收到响应时,会触发
-(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)aResponse{
NSLog(@"请求成功!");
returnInfoData=[[NSMutableDataalloc]init];
totalSize=
[aResponseexpectedContentLength];
NSHTTPURLResponse* httpResponse;
httpResponse = (NSHTTPURLResponse*)aResponse;
if((httpResponse.statusCode/100) !=2) {
NSLog(@"保存失败");
}else{
NSLog(@"保存成功");
}
}