OC网络:文件上传

2015-12-10  本文已影响449人  cyh老崔

其中KFileBoundary的名称可以自定义.


#define KFileBoundary @"fanlu"
#define KNewLine @"\r\n"
#define KEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]


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

//基本构成为两个参数:文件参数与用户名参数.每个参数配置时的规则:先配置文件信息,再配置具体数据.
/*
 参数1
 参数2
 结束标记
 */

/*
 * 文件参数 :1.配置文件信息 2.配置具体文件数据
 fanlu
 Content-Disposition: form-data; name="参数名"; filename="文件名"
 Content-Type: 文件类型(MIMEType)
 
 文件具体数据
 
 * 非文件参数: 1.配置参数信息 2.配置具体参数值
 fanlu
 Content-Disposition: form-data; name="参数名"
 
 参数值
 */

- (void)upload
{
    // 1.请求路径
    NSURL *url = [NSURL URLWithString:@"http://192.168.15.172:8080/Server/upload"];
    
    // 2.创建一个POST请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    // 3.设置请求体
    NSMutableData *body = [NSMutableData data];
    
    // 3.1.文件参数
    [body appendData:KEncode(@"--")];
    [body appendData:KEncode(KFileBoundary)];
    [body appendData:KEncode(KNewLine)];
    
    [body appendData:KEncode(@"Content-Disposition: form-data; name=\"file\"; filename=\"test123.png\"")];
    [body appendData:KEncode(KNewLine)];
    
    [body appendData:KEncode(@"Content-Type: image/png")];
    [body appendData:KEncode(KNewLine)];
    
    [body appendData:KEncode(KNewLine)];
    UIImage *image = [UIImage imageNamed:@"minion_03"];
    NSData *imageData = UIImagePNGRepresentation(image);
    [body appendData:imageData];
    [body appendData:KEncode(KNewLine)];
    
    // 3.2.用户名参数
    [body appendData:KEncode(@"--")];
    [body appendData:KEncode(KFileBoundary)];
    [body appendData:KEncode(KNewLine)];
    
    //直接复制上述字符串,将filename及类型去掉.因为不是文件参数,所以不需要filename及类型
    [body appendData:KEncode(@"Content-Disposition: form-data; name=\"username\"")];
    [body appendData:KEncode(KNewLine)];
    
    [body appendData:KEncode(KNewLine)];
    [body appendData:KEncode(@"张三")];
    [body appendData:KEncode(KNewLine)];
    
    // 3.3.结束标记
    [body appendData:KEncode(@"--")];
    [body appendData:KEncode(KFileBoundary)];
    [body appendData:KEncode(@"--")];
    [body appendData:KEncode(KNewLine)];
    
    request.HTTPBody = body;
    
    // 4.设置请求头(告诉服务器这次传给你的是文件数据,告诉服务器现在发送的是一个文件上传请求)
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", KFileBoundary];
    [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);
    }];
}
上一篇下一篇

猜你喜欢

热点阅读