zoukankan      html  css  js  c++  java
  • 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]; //上传成功之后执行你想进行的操作

            }

       }

     

     

  • 相关阅读:
    地球人找工作之笔霸传奇
    地球人找工作之简历的秘密
    地球人找工作之前期准备
    Swift中的一些关键字
    swift动画小试牛刀
    【extjs6学习笔记】1.8 初始: ExtJS命名约定
    【extjs6学习笔记】1.7 初始:加载第三方库
    【extjs6学习笔记】1.6 初始:本地化
    【extjs6学习笔记】0.1 准备:基础概念(02)
    【extjs6学习笔记】1.5 初始:关于布局
  • 原文地址:https://www.cnblogs.com/paocai2015/p/5072336.html
Copyright © 2011-2022 走看看