1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #import "ViewController.h" #define FileBoundary @"boundary" #define NewLien @"\r\n" #define Encode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
@interface ViewController () @end
@implementation ViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self upload]; } - (void)upload { // 1.请求路径 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/upload"]; // 2.创建一个POST请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; // 3.设置请求体 NSMutableData *body = [NSMutableData data]; // 3.1.文件参数 [body appendData:Encode(@"--")]; [body appendData:Encode(FileBoundary)]; [body appendData:Encode(NewLien)]; [body appendData:Encode(@"Content-Disposition: form-data; name=\"file\"; filename=\"test123.png\"")]; [body appendData:Encode(NewLien)]; [body appendData:Encode(@"Content-Type: image/png")]; [body appendData:Encode(NewLien)]; [body appendData:Encode(NewLien)]; UIImage *image = [UIImage imageNamed:@"minion_03"]; NSData *imageData = UIImagePNGRepresentation(image); [body appendData:imageData]; [body appendData:Encode(NewLien)]; // 3.2.用户名参数 [body appendData:Encode(@"--")]; [body appendData:Encode(FileBoundary)]; [body appendData:Encode(NewLien)]; [body appendData:Encode(@"Content-Disposition: form-data; name=\"username\"")]; [body appendData:Encode(NewLien)]; [body appendData:Encode(NewLien)]; [body appendData:Encode(@"张三")]; [body appendData:Encode(NewLien)]; // 3.3.结束标记 [body appendData:Encode(@"--")]; [body appendData:Encode(FileBoundary)]; [body appendData:Encode(@"--")]; [body appendData:Encode(NewLien)]; request.HTTPBody = body; // 4.设置请求头(告诉服务器这次传给你的是文件数据,告诉服务器现在发送的是一个文件上传请求) NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", FileBoundary]; [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; // 5.发送请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@", dict); NSLog(@"%@",data); }]; } @end
|