AFNetworking2.0 AFHTTPRequestOperationManager实现上传、下传


AFHTTPRequestOperationManager实现在任意格式数据下载,网上查找只有上传,下载图片的资料。

1、上传示例

AFHTTPRequestOperationManager *requestManager = [[AFHTTPRequestOperationManager alloc] init];
    requestManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [requestManager POST:@"http://192.168.165.68:8080/xxxxx/fileController/upload.action" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"时钟.zip" ofType:nil]];
        
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        [dictionary setObject:@"multipart/form-data" forKey:@"Content-Type"];
        [dictionary setObject:[NSNumber numberWithInteger:data.length] forKey:@"Content-Length"];
        [dictionary setObject:@"form-data; name=\"f2\"; filename=\"时钟.zip\"" forKey:@"Content-Disposition"];
    
        [formData appendPartWithHeaders:dictionary body:data];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //  服务器返回JSON的数据
        NSLog(@"content = %@", [responseObject objectForKey:@"content"]);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@", error);
    }];



根据实际情况进行修改,服务器返回数据的时候,需设置response的ContentType设置为"text/json;charset=UTF-8。否则success块将不会被调用。

2、下载示例

    AFHTTPRequestOperationManager *requestManager = [[AFHTTPRequestOperationManager alloc] init];
    requestManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [requestManager POST:@"http://192.168.165.68:8080/xxxx/fileController/download.action" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *headers = operation.response.allHeaderFields;
        
        // 解析下载文件名
        NSString *content = [headers objectForKey:@"Content-Disposition"];
        NSString *fileName = [[content componentsSeparatedByString:@"="] lastObject];
        
        // 保存文件
        NSString *destPath = [NSString stringWithFormat:@"%@/tmp/%@", NSHomeDirectory(), [fileName lastPathComponent]];
        [operation.responseData writeToFile:destPath atomically:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@", error);
    }];



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值