美文网首页
NSURLSession上传小文件

NSURLSession上传小文件

作者: solozyx | 来源:发表于2016-08-07 23:32 被阅读38次
    #import "ViewController.h"
    
    #define     ZYXBoundary         @"520it"
    #define     ZYXEncode(string)   [string dataUsingEncoding:NSUTF8StringEncoding]
    #define     ZYXNewLine          [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
    
    @interface ViewController () 
    /** session */
    @property (nonatomic, strong) NSURLSession *session;
    @end
    
    @implementation ViewController
    
    - (NSURLSession *)session{
        if (!_session) {
            NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
            cfg.timeoutIntervalForRequest = 10;
            // 是否允许使用蜂窝网络(手机自带网络)
            cfg.allowsCellularAccess = YES;
            _session = [NSURLSession sessionWithConfiguration:cfg];
        }
        return _session;
    }
    
    - (void)uploadFile{
        NSString *urlString = @"http://www.example.com:8080/upload";
        NSURL *url = [NSURL URLWithString:urlString];
        NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
        requestM.HTTPMethod = @"POST";
        
        // 设置请求头(告诉服务器,这是一个文件上传的请求)
        [requestM setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", ZYXBoundary] forHTTPHeaderField:@"Content-Type"];
        
        // 设置请求体
        NSMutableData *body = [NSMutableData data];
        
        // 文件参数
        // 分割线
        [body appendData:ZYXEncode(@"--")];
        [body appendData:ZYXEncode(ZYXBoundary)];
        [body appendData:ZYXNewLine];
        
        // 文件参数名
        [body appendData:ZYXEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
        [body appendData:ZYXNewLine];
        
        // 文件的类型
        [body appendData:ZYXEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
        [body appendData:ZYXNewLine];
        
        // 文件数据
        [body appendData:ZYXNewLine];
        [body appendData:[NSData dataWithContentsOfFile:@"/Users/zhaoyingxin/Desktop/test.png"]];
        [body appendData:ZYXNewLine];
        
        // 结束标记
        /*
         --分割线--\r\n
         */
        [body appendData:ZYXEncode(@"--")];
        [body appendData:ZYXEncode(ZYXBoundary)];
        [body appendData:ZYXEncode(@"--")];
        [body appendData:ZYXNewLine];
        
        [[self.session uploadTaskWithRequest:requestM
                                    fromData:body
                           completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                               NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
                           }]
         resume];
    }
    
    //{success : 上传成功}
    //{error : 上传失败}
    

    相关文章

      网友评论

          本文标题:NSURLSession上传小文件

          本文链接:https://www.haomeiwen.com/subject/nhnlsttx.html