您的位置:首页 > 理论基础 > 计算机网络

iOS网络 POST模拟表单上传单个与多个文件(直接调用分类里的方法即可)

2015-02-17 16:17 691 查看
//
//  ViewController.m
//  01-POST上传文件
//
//  Created by 刘凡 on 15/2/8.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "ViewController.h"
#import "NSMutableURLRequest+Multipart.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self multiPostUpload];
}

// MARK: - 多个文件上传
- (void)multiPostUpload {
NSURL *url = [NSURL URLWithString:@"http://localhost/post/upload-m.php"];

NSURL *fileUrl1 = [[NSBundle mainBundle] URLForResource:@"demo.jpg" withExtension:nil];
NSData *data1 = [NSData dataWithContentsOfURL:fileUrl1];
NSURL *fileURL2 = [[NSBundle mainBundle] URLForResource:@"001.png" withExtension:nil];
NSData *data2 = [NSData dataWithContentsOfURL:fileURL2];
NSArray *dataArray = @[data1, data2];
NSArray *fileNames = @[@"demo.jpg", @"001.png"];

//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url keyName:@"userfile" fileDataArray:dataArray fileNames:fileNames];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url keyName:@"userfile" fileURLs:@[fileUrl1, fileURL2] fileNames:fileNames];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url keyName:@"userfile" fileURLs:@[fileUrl1, fileURL2]];

// 3. connection
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]);
}];
}

// MARK: - 单个文件上传
- (void)postUpload {
// 1. url
NSURL *url = [NSURL URLWithString:@"http://localhost/post/upload.php"];

// 2. request
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"demo.jpg" withExtension:nil];
NSData *data = [NSData dataWithContentsOfURL:fileUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url keyName:@"userfile" fileData:data fileName:@"bcd.jpg"];

// 3. connection
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]);
}];
}

@end

http://pan.baidu.com/s/1ntqTaWT
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: