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

            }

       }

     

     

  • 相关阅读:
    树状数组|求逆序数
    Mapreduce之分区与自定义计数器
    yb课堂 前端项目目录结构创建和讲解 《三十三》
    yb课堂 VueCli 4.3搭建yb课堂前端项目架构 《三十二》
    yb课堂 ECMAScript 6常见语法快速入门 《三十一》
    yb课堂 前端项目技术组件概述 《三十》
    yb课堂 新版VueCli 4.3创建vue项目,Vue基础语法入门 《二十九》
    yb课堂 新版Vue+脚手架Vue-Cli 4.3安装 《二十七》
    yb课堂 搭建node环境和npm安装 《二十六》
    yb课堂 VSCODE编译器和开发环境搭建 《二十五》
  • 原文地址:https://www.cnblogs.com/paocai2015/p/5072336.html
Copyright © 2011-2022 走看看