iOS网络 AFN简单的上传 与 session上传带进度数据
博客专区 > 沉恋 的博客 > 博客详情
iOS网络 AFN简单的上传 与 session上传带进度数据
沉恋 发表于3年前
iOS网络 AFN简单的上传 与 session上传带进度数据
  • 发表于 3年前
  • 阅读 152
  • 收藏 1
  • 点赞 0
  • 评论 0

【腾讯云】如何购买服务器最划算?>>>   

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

//
//  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

共有 人打赏支持
粉丝 9
博文 55
码字总数 63031
×
沉恋
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: