首页 > 解决方案 > Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function

问题描述

Uncaught (in promise) TypeError: window.showOpenFilePicker() is not a function

我正在尝试阅读和写作,File System Web API但我不断得到TypeError Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function,我不知道发生了什么。

这是反应代码片段:

const FileReader = () => {
    const openThisFile = async () => {
        const [fileHandle] = await window.showOpenFilePicker(); // error: Property 'showOpenFilePicker' does not exist on type 'Window & typeof globalThis'
        console.log(fileHandle);
    };
    return (
        <div>
            <button onClick={openThisFile}>Open file</button>
        </div>
    );
};

export default FileReader;

所以我认为它在反应中不起作用,然后我尝试了 Vanilla Javascript,但我仍然继续进入TypeError Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function控制台。这是代码片段。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Open file</title>
    </head>
    <body>
        <button onclick="getFile()">Open file</button>
        <script>
            const pickerOpts = {
                types: [
                    {
                        description: "Images",
                        accept: {
                            "image/*": [".png", ".gif", ".jpeg", ".jpg"],
                        },
                    },
                ],
                excludeAcceptAllOption: true,
                multiple: false,
            };

            let fileHandle;
            async function getFile() {
                [fileHandle] = await window.showOpenFilePicker(pickerOpts);
                // run code with our fileHandle
            }
            console.log(fileHandle);
        </script>
    </body>
</html>

知道我做错了什么吗?

标签: javascriptreactjs

解决方案


我想你看到上面的问题是因为以下原因:

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

考虑查看文档:https ://developer.mozilla.org/en-US/docs/Web/API/Window/showOpenFilePicker


推荐阅读