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

            }

       }

     

     

  • 相关阅读:
    Gradle在大型Java项目上的应用
    Spring MVC 构建入门级 Web 应用程序
    大公司最喜欢问的Java集合类面试题
    在Java中正确使用注释
    Java的wait(), notify()和notifyAll()使用心得
    Java中HashMap和TreeMap的区别深入理解
    初识PGM图片
    VS2013报错 error MSB8031解决方法
    matconvnet在MATLAB2013配置过程中遇到的问题
    配置VLFeat-0.9.20+MATLAB2013a
  • 原文地址:https://www.cnblogs.com/paocai2015/p/5072336.html
Copyright © 2011-2022 走看看