用NSInputStream 来实现图片上传

原文来自http://blog.sina.com.cn/s/blog_7b9d64af01019qdr.html

1.准备工作,将需要的类进行声明定义。
*.h 文件

NSURLConnection* _aSynConnection;

NSInputStream *_inputStreamForFile;

NSString *_localFilePath;


@property (nonatomic,retain) NSURLConnection* aSynConnection;

@property (nonatomic,retainNSInputStream *inputStreamForFile;

@property (nonatomic,retain) NSString *localFilePath;


*.m 文件

@synthesize inputStreamForFile=_inputStreamForFile;

@synthesize localFilePath=_localFilePath;

@synthesize aSynConnection=_aSynConnection;


2.进行请求


// 我将其写入按钮事件中

- (void)btnClickAction:(id)sender{

    NSLog(@"--------btnClickAction--------");

    

    // 初始化目标地址的URL(发送到哪里)

    NSURL *serverURL;

    NSString *strURL=@"http://www.xxx.com/fileName.png";// 这里用图片为例

strURL = [strURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

    serverURL=[NSURL URLWithString:strURL];

    

    // 初始化本地文件路径,并与NSInputStream链接

    self.localFilePath=@"本地的图片路径";

    self.inputStreamForFile = [NSInputStream inputStreamWithFileAtPath:self.localFilePath];

    

    // 上传大小

    NSNumber *contentLength;

    contentLength = (NSNumber *) [[[NSFileManager defaultManager]attributesOfItemAtPath:self.localFilePath error:NULL] objectForKey:NSFileSize];

    

   

    NSMutableURLRequest *request;

    request = [NSMutableURLRequest requestWithURL:serverURL];

    [request setHTTPMethod:@"PUT"];

    [request setHTTPBodyStream:self.inputStreamForFile];

    [request setValue:@"image/png" forHTTPHeaderField:@"Content-Type"];

    [request setValue:[contentLength description] forHTTPHeaderField:@"Content-Length"];

    

    // 请求

    self.aSynConnection = [NSURLConnection connectionWithRequest:requestdelegate:self];

    


}


3.接受回调函数的状态,判断是否上传成功。


// 收到响应时,会触发

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)aResponse{

    NSLog(@"请求成功!");

    returnInfoData=[[NSMutableData alloc]init];

    totalSize= [aResponse expectedContentLength];

    

    NSHTTPURLResponse * httpResponse;

    httpResponse = (NSHTTPURLResponse *)aResponse;

    if ((httpResponse.statusCode / 100) != 2) {

        NSLog(@"保存失败");

    } else {

        NSLog(@"保存成功");

    }

}

原文来自http://blog.sina.com.cn/s/blog_7b9d64af01019qdr.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值