情境
有時候,我們需要儲存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