iOS网络 AFN简单的上传 与 session上传带进度数据

中间的拼接可以写个分类以简化

//
//  ViewController.m
//  AFN尝试
//
//  Created by chen on 15/2/22.
//  Copyright (c) 2015年 lanrw. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController () <NSURLSessionTaskDelegate>
@property (nonatomic, strong) NSURLSession *session;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    /**
     *  简单上传文件
     */
//    [self uploadFile];
    /**
     *  可打印出文件上传的进度条数据
     */
    [self uploadFile2];
}

/**
 *  不需要拼接也可以上传文件 (无进度数据)
 */
- (void)uploadFile
{
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger POST:@"http://localhost/post/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSURL *url = [[NSBundle mainBundle]URLForResource:@"music.mp3.zip" withExtension:nil];
        [formData appendPartWithFileURL:url name:@"userfile" fileName:@"1.zip" mimeType:@"application/octet-stream" error:NULL];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"上传成功");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"上传失败");
    }];
}

/**
 *  使用session上传 有进度条数据
 */
- (void)uploadFile2
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/post/upload.php"]cachePolicy:1 timeoutInterval:7];
    
    request.HTTPMethod = @"post";
    
    // boundary可随意命名
    NSString *boundary = @"chen";
    
    // 拼接请求头
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];
    
    // 创建可变data 后面一样拼接
    NSMutableData *myData = [NSMutableData data];
    
    NSString *str = [NSString stringWithFormat:@"--%@\n",boundary];
    [myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    
    // html页面上传表单里的 <input type="file" name="userfile">
    NSString *name = @"userfile";
    // 上传后文件的名字
    NSString *filename = @"1.zip";
    
    str = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\n",name,filename];
    [myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    
    str = @"Content-Type: application/octet-stream\n\n";
    [myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    
    // bundle中的文件转换成二进制数据
    NSURL *uploadFile = [[NSBundle mainBundle]URLForResource:@"music.mp3.zip" withExtension:nil];
    [myData appendData:[NSData dataWithContentsOfURL:uploadFile]];
    
    str = [NSString stringWithFormat:@"\n\n--%@--",boundary];
    [myData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    
    request.HTTPBody = myData;
    [[self.session uploadTaskWithRequest:request fromData:myData]resume];
}

#pragma mark - 检测上传进度
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
   didSendBodyData:(int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    float progress = (float)totalBytesSent / totalBytesExpectedToSend;
    NSLog(@"%f %@", progress, [NSThread currentThread]);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"完成");
}

// 懒加载
- (NSURLSession *)session
{
    if(_session == nil)
    {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}

@end



http://pan.baidu.com/s/1pJqjflT

转载于:https://my.oschina.net/lanrenbar/blog/379512

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值