中间的拼接可以写个分类以简化
//
// 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