开发身份证验证功能时,要求以formData形式将身份证正反面图片上传到服务器,实现部分代码如下:
AFHTTPSessionManager *imageManager = [AFHTTPSessionManager manager]; imageManager.responseSerializer = [AFHTTPResponseSerializer serializer]; //url为身份证上传到服务器的完整地址 [imageManager POST:url parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { //上传身份证图片 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyyMMddHHmmss"; NSString *str = [formatter stringFromDate:[NSDate date]]; NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str]; //将身份证正反面图片的二进制文件拼在一起(name后面的value一定要跟后台给的接口文档的key一致) //idCardFrontImg、idCardbackImg为身份证正/反面图片,UIImage类型 [formData appendPartWithFileData:UIImageJPEGRepresentation(idCardFrontImg, 0.5) name:@"frontFile" fileName:fileName mimeType:@"image/jpeg"]; [formData appendPartWithFileData:UIImageJPEGRepresentation(idCardbackImg, 0.5) name:@"backFile" fileName:fileName mimeType:@"image/jpeg"]; } progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //上传成功 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //上传失败 }];