NSURLSession 实现文件上传

//
//  ViewController.m
//  11NSURLSession实现文件上传
//
//  Created by kun on 16/8/14.
//  Copyright © 2016年 kun. All rights reserved.
//

#import "ViewController.h"

#define Kboundary @"----WebKitFormBoundaryjv0UfA04ED44AhWx"
#define KNewLine [@"
" dataUsingEncoding:NSUTF8StringEncoding]

@interface ViewController ()<NSURLSessionDataDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
}
- (void)upload
{
    // url
    NSURL *url = [NSURL URLWithString:@""];
    // 创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 设置请求方法
    request.HTTPMethod = @"POST";
    // 设置请求头信息
    [request setValue:[NSString stringWithFormat:@"multipart/form-data:boundary=%@", Kboundary] forHTTPHeaderField:@"Content-Type"];
    // 创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    // 创建上传Task
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:[self getBodyData] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    }];
    // 执行Task
    [uploadTask resume];
}
- (void)upload2
{
    // url
    NSURL *url = [NSURL URLWithString:@""];
    // 创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 设置请求方法
    request.HTTPMethod = @"POST";
    // 设置请求头信息
    [request setValue:[NSString stringWithFormat:@"multipart/form-data:boundary=%@", Kboundary] forHTTPHeaderField:@"Content-Type"];
    // 创建会话对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    // 创建上传Task
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:[self getBodyData] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    }];
    // 执行Task
    [uploadTask resume];
}
#pragma mark - NSURLSessionDataDelegate
/**
 *  @param bytesSent                本次发送的数据
 *  @param totalBytesSent           上传完成的数据大小
 *  @param totalBytesExpectedToSend 文件的总大小
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    NSLog(@"%f", 1.0 * totalBytesSent / totalBytesExpectedToSend );
}
- (NSData *)getBodyData
{
    NSMutableData *fileData = [NSMutableData data];
    // 文件参数
    /*
     --分隔符
     Content-Disposition: form-data; name="file";
        filename="Snip20160225_341.png"
     Content-Type: image/png(MIMEType:大类型/小类型)
     空行
     文件参数
     */
    [fileData appendData:[[NSString stringWithFormat:@"--%@", Kboundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    // name:file 服务器规定的参数
    // filename:Snip20160225_341.png 文件保存到服务器上面的名称
    // Content-Type: 文件的类型
    [fileData appendData:[@"Content-Disposition: form-data; name="file"; filename="Snip2016225_341.png"" dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    [fileData appendData:[@"Content-Type: image/png" dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    [fileData appendData:KNewLine];
    
    UIImage *image = [UIImage imageNamed:@"Snip2016225_341"];
    // UImage --> NSData
    NSData *imageData = UIImagePNGRepresentation(image);
    [fileData appendData:imageData];
    [fileData appendData:KNewLine];
    
    // 非文件参数
    /*
     --分隔符
     Content-Disposition: form-data; name="username"
     空行
     12345
     */
    [fileData appendData:[[NSString stringWithFormat:@"--%@", Kboundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    [fileData appendData:[@"Conten-Disposition: form-data; name="username"" dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    [fileData appendData:KNewLine];
    [fileData appendData:[@"12345" dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    
    // 结尾标识
    /*
     --分隔符--
     */
    [fileData appendData:[[NSString stringWithFormat:@"--%@--", Kboundary] dataUsingEncoding:NSUTF8StringEncoding]];
    return fileData;
}
@end
原文地址:https://www.cnblogs.com/fkunlam/p/5769463.html