NSURLSession文件上传(前台上传)

NSURLSession提供的文件上传接口,并不比NSURLConnection简单,同样需要在NSData中构建HTTP固定的格式,下面介绍其用法。

配置session

  • 代码
 NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

 NSURLSession *downloadSession = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  • 代码说明
    将session配置为默认session,并设置session的回调在主线程,不多说。

配置request

  • 代码
NSURL *url = [NSURL URLWithString:@"http://localhost/upload.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
request.HTTPMethod = @"post";
  • 代码说明
    首先通过URL生成一个request,如果是上传文件,header中的Content-Type的值必须设置为:multipart/form-data; boundary=xxxxxx,xxxxxx用于判断文件的边界,可以是任意值,一般设置一个随机的字符串.最后,设置了httpMethod为post,文件上传的默认方法为post,也可以是put,但不常用

配置上传的文件

  • 代码
- (NSData *)getSendDataWithFilePath:(NSString *)path
{
    NSMutableData *data = [NSMutableData data];
    // 表单拼接
    NSMutableString *headerStrM =[NSMutableString string];
    [headerStrM appendFormat:@"--%@\r\n",boundary];
    // name:表单控件名称  filename:上传文件名
    [headerStrM appendFormat:@"Content-Disposition: form-data;   name=%@; filename=%@\r\n",@"userfile",@"test.txt"];
    [headerStrM appendFormat:@"Content-Type: %@\r\n\r\n",@"text/plain"];
    [data appendData:[headerStrM dataUsingEncoding:NSUTF8StringEncoding]];
    
    // 文件内容
    NSData *fileData = [NSData dataWithContentsOfFile:path];
    [data appendData:fileData];
    
    NSMutableString *footerStrM = [NSMutableString stringWithFormat:@"\r\n--%@--\r\n",boundary];
    [data appendData:[footerStrM  dataUsingEncoding:NSUTF8StringEncoding]];
    
    return data;
}
  • 代码说明
    http协议上传文件有固定的格式:
    --boundary\r\n

Content-Disposition: form-data; name="<服务器端需要知道的名字>"; filename="<服务器端这个传上来的文件名>"
Content-Type: application/zip --根据不同的文件类型选择不同的值

<空行>

<二进制数据>

--boundary--\r\n
该格式是固定的,上述代码也只是按照上述格式,封装了一个NSData.需要注意的是Content-Disposition: form-data; name="<服务器端需要知道的名字>"; 这个需要服务端告诉name的值.设置好了这些遍可以上传数据了.这个格式看似复杂,其实是固定的,设置正确就行.

开始上传

NSURLSessionUploadTask *uploadTask =  [uploadSession uploadTaskWithRequest:request fromData:[self getSendDataWithFilePath:filePath]];
[uploadTask resume];

生成一个上传任务,并开始上传,这没什么可说的

处理回调

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    NSLog(@"bytesSent=%@",@(bytesSent));
    NSLog(@"totalBytesSent=%@",@(totalBytesSent));
    NSLog(@"totalBytesExpectedToSend=%@",@(totalBytesExpectedToSend));
}

系统并没有专门为上传提供回调方法,但是我们能利用NSURLSessionTask的回调方法,上述方法是在数据传输过程中调用的方法.

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    NSLog(@"response=%@",response);
    completionHandler(NSURLSessionResponseAllow);
}

当数据传送完成之后,系统回根据服务端返回的response进行处理

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if ( error ) {
        NSLog(@"存在错误%@",error);
        return;
    }
    NSLog(@"文件上传完成");
}

NSURLSession的任何task完成之后,都会执行该回调

你可能感兴趣的:(NSURLSession文件上传(前台上传))