1.添加协议
<NSURLConnectionDelegate>
2.创建
@property (nonatomic,retain) NSURLConnection* aSynConnection;
@property (nonatomic,retain) NSInputStream *inputStreamForFile;
@property (nonatomic,retain) NSString *localFilePath;
3.创建请求
NSString *path=[[NSBundle mainBundle] pathForResource:str ofType:@"bin"];// 获取需要上传的文件的路径
NSString *urlStr = [NSString stringWithFormat:@"http://%@/device/bin/upgrade/?bin=%@.bin",UrlStr,userBin];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL *serverURL=[NSURL URLWithString:urlStr];//上传的服务器地址
self.inputStreamForFile = [NSInputStream inputStreamWithFileAtPath:path];
NSNumber *contentLength = (NSNumber *) [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:NULL] objectForKey:NSFileSize];
NSMutableURLRequest *request;
request = [NSMutableURLRequest requestWithURL:serverURL];
[request setHTTPMethod:@"POST"];
[request setHTTPBodyStream:self.inputStreamForFile];
[request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];//这里设置文件上传的协议 当前协议时以任何流形式上传
[request setValue:[contentLength description] forHTTPHeaderField:@"Content-Length"];
self.aSynConnection = [NSURLConnection connectionWithRequest:request delegate:self];//添加代理方法
4.实现代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse{
NSLog(@"请求成功!");
NSHTTPURLResponse * httpResponse;
httpResponse = (NSHTTPURLResponse *)aResponse;
if ((httpResponse.statusCode / 100) != 2) {
NSLog(@"保存失败");
} else {
NSLog(@"保存成功");
[self UpDataTheDeviceAndReset]; //上传成功之后执行你想进行的操作
}
}