请问是否存在window.showOpenFilePicker的Polyfill?(MDN相关技术问询)
Is there a polyfill for
window.showOpenFilePicker? Great question! Let's dive into this.
First, a quick reminder: window.showOpenFilePicker is part of the File System Access API, which brings more flexible local file interaction to web apps compared to the old-school <input type="file">.
Now, onto polyfills:
- There’s no full polyfill that replicates every feature of
showOpenFilePicker. The core issue is that this API relies on browser-specific permission systems for persistent file/folder access—something that can’t be fully emulated in environments that don’t support the native API. - That said, you can easily build a partial polyfill using the classic file input element to cover the basic "select files" use case. Here’s a practical example:
async function showOpenFilePickerPolyfill(options = {}) { return new Promise((resolve, reject) => { const input = document.createElement('input'); input.type = 'file'; // Mirror native options if (options.multiple) input.multiple = true; if (options.types?.length) { input.accept = options.types .map(type => Object.keys(type.accept).join(',')) .join(','); } input.addEventListener('change', () => { if (!input.files.length) return reject(new Error('No files selected')); // Mimic the native FileSystemFileHandle structure const handles = Array.from(input.files).map(file => ({ async getFile() { return file; }, name: file.name, type: file.type })); resolve(handles); }); input.addEventListener('cancel', () => reject(new Error('Selection cancelled'))); input.click(); }); } // How to use it async function pickFiles() { try { const handles = window.showOpenFilePicker ? await window.showOpenFilePicker({ multiple: true }) : await showOpenFilePickerPolyfill({ multiple: true }); for (const handle of handles) { const file = await handle.getFile(); console.log('Selected file:', file.name); } } catch (err) { console.error(err.message); } }
- This fallback works for basic file selection, but it has key limitations: no persistent access to files, no support for folder selection, and no ability to write changes back to files—all things that make the native File System Access API so useful. But it’s a solid stopgap for older browsers.
- If you don’t want to build the polyfill yourself, some community-maintained libraries wrap this fallback logic alongside other File System Access API fallbacks, handling edge cases more gracefully than a simple custom implementation.
内容的提问来源于stack exchange,提问作者Lenard
相关产品推荐
相关产品推荐

