iOS开发中文件的上传和下载功能的基本实现

2020-01-14 17:11:52于海丽

    [body appendData:data];
    [body appendData:YYEncode(@"rn")];
    
    /***************普通参数***************/
    [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        // 参数开始的标志
        [body appendData:YYEncode(@"--YYrn")];
        NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name="%@"rn", key];
        [body appendData:YYEncode(disposition)];

        [body appendData:YYEncode(@"rn")];
        [body appendData:YYEncode(obj)];
        [body appendData:YYEncode(@"rn")];
    }];
    
    /***************参数结束***************/
    // YY--rn
    [body appendData:YYEncode(@"--YY--rn")];
    request.HTTPBody = body;
    
    // 设置请求头
    // 请求体的长度
    [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
    // 声明这个POST请求是个文件上传
    [request setValue:@"multipart/form-data; boundary=YY" 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(@"上传失败");
        }
    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // Socket 实现断点上传
    
    //apache-tomcat-6.0.41/conf/web.xml 查找 文件的 mimeType