码迷,mamicode.com
首页 > 其他好文 > 详细

网络编程练习 -- 文件上传

时间:2014-07-03 23:07:34      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   文件   os   

LWTViewController.m

bubuko.com,布布扣
//
//  LWTViewController.m
//  网络编程练习 -- 文件上传
//
//  Created by apple on 14-6-30.
//  Copyright (c) 2014年 lwt. All rights reserved.
//

#import "LWTViewController.h"
#define KStringToData(string) [string dataUsingEncoding:NSUTF8StringEncoding]

@interface LWTViewController ()

@end

@implementation LWTViewController

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

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 获取文件类型和data
    NSURL *imageUrl = [[NSBundle mainBundle] URLForResource:@"test.png" withExtension:nil];
    NSURLRequest *imageRequest = [NSURLRequest  requestWithURL:imageUrl];
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:imageRequest returningResponse:&response error:nil];
    NSString *mimeType = response.MIMEType;
    
    [self upload:@"file" fileName:@"test.png" mimeType:mimeType data:data params:@{
                                                                                   @"username" : @"999",
                                                                                   @"type" : @"XML"
                                                                                   }];
    
    
    
}

- (void)upload: (NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType data:(NSData *)data params :(NSDictionary *)params
{
    // 文件上传
    NSURL *url = [NSURL URLWithString:[@"http://192.168.1.24:8080/MJServer/upload" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    
    
    // 设置请求体
    NSMutableData *body = [NSMutableData data];
    
    /***************文件参数***************/
    // 参数开始的标志
    [body appendData:KStringToData(@"--upload\r\n")];
    // name : 指定参数名(必须跟服务器端保持一致)
    // filename : 文件名
    NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, fileName];
    [body appendData:KStringToData(disposition)];
    
    NSString *str = [NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType];
    [body appendData:KStringToData(str)];
    
    [body appendData:KStringToData(@"\r\n")];
    [body appendData:data];
    [body appendData:KStringToData(@"\r\n")];
    
    /***************普通参数***************/
    [body appendData:KStringToData(@"--upload\r\n")];
    [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [body appendData:KStringToData(@"--upload\r\n")];
        NSString *dispos = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", key];
        [body appendData:KStringToData(dispos)];
        [body appendData:KStringToData(@"\r\n")];
        [body appendData:KStringToData(obj)];
        [body appendData:KStringToData(@"\r\n")];
    }];
    
    [body appendData:KStringToData(@"--heima--\r\n")];
    request.HTTPBody = body;
    
    // 设置请求头
    // 请求体的长度
    [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
    // 声明这个POST请求是个文件上传
    [request setValue:@"multipart/form-data; boundary=upload" forHTTPHeaderField:@"Content-Type"];
    
    // 发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"%@", dict);
        } else {
            NSLog(@"上传失败");
        }
    }];
}
@end
View Code

 

网络编程练习 -- 文件上传,布布扣,bubuko.com

网络编程练习 -- 文件上传

标签:style   blog   http   color   文件   os   

原文地址:http://www.cnblogs.com/wentianblog/p/3820771.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!