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);
}];