用輸入資料流NSInputStream 來實現圖片,檔案等的上傳

來源:互聯網
上載者:User
情境

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.