#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上传小文件
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- NSURLSession提供的文件上传接口,并不比NSURLConnection简单,同样需要在NSData中构建...
- 由于项目还在开发阶段,只能贴上部分代码,敬请谅解; 注意点: 在后台上传必须是调用此方法:uploadTaskWi...
- NSURLSession系列笔记:NSURLSession笔记 文件下载 总体思路和NSURLConnectio...
- 使用NSURLSession实现文件上传 本demo实现的功能是使用NSURLSession实现文件的上传,需要注...