场景: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(@"保存成功");
}
}