• 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]; //上传成功之后执行你想进行的操作

            }

       }

     

     

  • 相关阅读:
    SignalR 持久链接 (该功能为手机设备与后台同个用户id进行实现的,仅用signalR学习参考)
    SQL SERVER 分割符转列
    js时间计算加减
    SQL查询历史执行语句
    MSSQL 多行数据串联字符分割单行
    居于HttpWebRequest的HTTP GET/POST请求
    硬件UDP读数AsynUdpClient
    SQL取分组数据的所有第一条数据
    Python 文件的使用
    Python 数据类型
  • 原文地址:https://www.cnblogs.com/paocai2015/p/5072336.html
Copyright © 2020-2023  润新知