在Angular+Capacitor Filesystem中如何筛选PDF文件与文件夹?
解决方案
要让文件选择器仅显示文件夹和PDF文档,无需修改addFile()方法,核心是调整对应的file输入元素的属性,同时在文件选择后增加筛选逻辑确保只处理PDF文件。
1. 修改模板中的文件选择器元素
找到你模板中标记为#filepicker的<input>元素,添加以下属性:
<input #filepicker type="file" style="display: none;" accept=".pdf" webkitdirectory directory multiple />
各属性作用:
accept=".pdf":告诉浏览器只筛选PDF格式的文件webkitdirectory/directory:允许选择文件夹(webkitdirectory兼容Chrome/Edge等WebKit内核浏览器,directory是标准属性)multiple:支持同时选择多个文件或文件夹
2. 优化fileSelected()方法(可选但推荐)
部分浏览器在启用文件夹选择时,可能会忽略accept属性,因此建议在代码中手动筛选PDF文件,确保只处理符合要求的文件:
async fileSelected($event) { console.log("$event", $event); // 将FileList转为数组,方便筛选 const allFiles = Array.from($event.target.files); // 筛选PDF文件(通过MIME类型或文件后缀判断) const pdfFiles = allFiles.filter(file => file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf') ); // 遍历处理每个PDF文件 for (const selected of pdfFiles) { let fileName = this.createFileNameAlt(selected.name); await write_blob({ directory: Directory.Documents, path: `${this.FILE_DIR}/${fileName}`, blob: selected, fast_mode: true, recursive: true, on_fallback(error) { console.error(error) } }); } }
注意事项
- 不同浏览器对
directory和accept的组合支持有差异,部分浏览器在选择文件夹时会展示所有文件,因此代码层的筛选逻辑是必要的兜底方案 - 如果只需要允许选择单个PDF文件(不需要选文件夹),可以移除
webkitdirectory和directory属性,仅保留accept=".pdf"
内容的提问来源于stack exchange,提问作者Thomas Degroot
相关产品推荐
相关产品推荐

