IOS NSURLConnection 文件上传

<span style="font-size:14px;"><strong>//
//  ViewController.m
//  UPLoadFile
//
//  Created by hq on 16/4/17.
//  Copyright © 2016年 hanqing. All rights reserved.
//

#import "ViewController.h"

//boundary
#define HQBoundary @"com.hq"

//换行
#define HQNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]

//将字符串编码
#define HQEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    NSString *urlString=@"http://xxxx/upload";
    
    NSString *name=@"file";
    
    NSString *fileName=@"flieName";
    
    NSString *fileMIMEType=@"image/jpeg";
    
    NSString *username=@"hq";
    
    
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    
    request.HTTPMethod=@"POST";
    
    //设置请求头
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",HQBoundary] forHTTPHeaderField:@"Content-Type"];
    
    //设置请求体
    NSMutableData *body=[NSMutableData data];
    
    
    //分割线
    [body appendData:HQEncode(@"--")];
    [body appendData:HQEncode(HQBoundary)];
    [body appendData:HQNewLine];
    
    
    //文件参数名
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=%@",name,fileName]dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:HQNewLine];
    
    //文件类型
    [body appendData:[[NSString stringWithFormat:@"Content-Type:%@",fileMIMEType] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:HQNewLine];
    

    //文件数据
    [body appendData:HQNewLine];
    UIImage *image=[UIImage imageNamed:@"2"];
    [body appendData:UIImagePNGRepresentation(image)];
    [body appendData:HQNewLine];

    
    
    //非文件参数
    
    //分割线
    [body appendData:HQEncode(@"--")];
    [body appendData:HQEncode(HQBoundary)];
    [body appendData:HQNewLine];
    
    
    //参数名
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@",username] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:HQNewLine];
    
    [body appendData:HQNewLine];
    [body appendData:HQEncode(@"hq")];
    [body appendData:HQNewLine];
    
    
    //结束标记
    [body appendData:HQEncode(@"--")];
    [body appendData:HQEncode(HQBoundary)];
    [body appendData:HQEncode(@"--")];
    [body appendData:HQNewLine];
    
    request.HTTPBody=body;
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:nil error:nil]);
        
    }];
    

}

@end
</strong></span>


你可能感兴趣的:(IOS NSURLConnection 文件上传)