原文:NSInputStream和NSMutableURLRequest-實(shí)現(xiàn)保存文件到服務(wù)器_貞娃兒_新浪博客?
有時(shí)候,我們需要保存iPhone本地的資源(圖片為例)到服務(wù)器的相應(yīng)路徑。那么就需要將本地圖片上傳到服務(wù)器。這樣,可以用NSInputStream+NSURLConnection+NSMutableURLRequest來實(shí)現(xiàn)圖片上傳。
1.準(zhǔn)備工作,將需要的類進(jìn)行聲明定義。
*.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.進(jìn)行請(qǐng)求
實(shí)現(xiàn)同步、異步請(qǐng)求
//我將其寫入按鈕事件中
-(void)btnClickAction:(id)sender{
NSLog(@"--------btnClickAction--------");
//初始化目標(biāo)地址的URL(發(fā)送到哪里)
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"];
//請(qǐng)求
self.aSynConnection= [NSURLConnectionconnectionWithRequest:requestdelegate:self];
}
3.接受回調(diào)函數(shù)的狀態(tài),判斷是否上傳成功。
//收到響應(yīng)時(shí),會(huì)觸發(fā)
-(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)aResponse{
NSLog(@"請(qǐng)求成功!");
returnInfoData=[[NSMutableDataalloc]init];
totalSize=
[aResponseexpectedContentLength];
NSHTTPURLResponse* httpResponse;
httpResponse = (NSHTTPURLResponse*)aResponse;
if((httpResponse.statusCode/100) !=2) {
NSLog(@"保存失敗");
}else{
NSLog(@"保存成功");
}
}