IOS--工作总结--post上传文件(以流的方式上传)
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];?//上傳成功之后執行你想進行的操作
? ? }
}
?
?
轉載于:https://www.cnblogs.com/paocai2015/p/5072336.html
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的IOS--工作总结--post上传文件(以流的方式上传)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转载] 说说JSON和JSONP,也许
- 下一篇: Jenkins FTP 上传