場景:html
有時候,咱們須要保存iPhone本地的資源(圖片爲例)到服務器的相應路徑。那麼就須要將本地圖片上傳到服務器。這樣,能夠用NSInputStream + NSURLConnection +NSMutableURLRequest來實現圖片上傳。服務器
1.準備工做,將須要的類進行聲明定義。異步
*.h 文件函數
NSURLConnection* _aSynConnection;atom
NSInputStream *_inputStreamForFile;spa
NSString *_localFilePath;orm
@property (nonatomic,retain) NSURLConnection* aSynConnection;server
@property (nonatomic,retain) NSInputStream *inputStreamForFile;htm
@property (nonatomic,retain) NSString *localFilePath;blog
*.m 文件
@synthesize inputStreamForFile=_inputStreamForFile;
@synthesize localFilePath=_localFilePath;
@synthesize aSynConnection=_aSynConnection;
2.進行請求
關於,使用進行請求的相關知識,能夠看我另外一篇博客,在這裏就再也不贅述了。
NSURLConnection和NSMutableURLRequest 實現同步、異步請求
// 我將其寫入按鈕事件中
- (void)btnClickAction:(id)sender{
NSLog(@"--------btnClickAction--------");
// 初始化目標地址的URL(發送到哪裏)
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:requestdelegate:self];
}
3.接受回調函數的狀態,判斷是否上傳成功。
// 收到響應時,會觸發
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse{
NSLog(@"請求成功!");
returnInfoData=[[NSMutableData alloc]init];
totalSize= [aResponse expectedContentLength];
NSHTTPURLResponse * httpResponse;
httpResponse = (NSHTTPURLResponse *)aResponse;
if ((httpResponse.statusCode / 100) != 2) {
NSLog(@"保存失敗");
} else {
NSLog(@"保存成功");
}
}