reactjs 未捕获(承诺中)TypeError:窗口. showOpenFilePicker不是函数

qmelpv7a  于 2023-03-08  发布在  React
关注(0)|答案(2)|浏览(383)

未捕获(在承诺中)类型错误:窗口.showOpenFilePicker()不是函数

我正在尝试用File System Web API进行阅读写实验,但是我一直得到TypeErrorUncaught (in promise) TypeError: window.showOpenFilePicker is not a function,我不知道发生了什么。
下面是react代码片段:

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;

所以我想它在react中不起作用,然后我尝试了Vanilla Javascript,但我仍然在控制台中得到TypeErrorUncaught (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>

你知道我做错了什么吗?

mcdcgff0

mcdcgff01#

我想您之所以看到上述问题是因为以下原因:
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

wbgh16ku

wbgh16ku2#

问题很可能出在你的浏览器上,截至2023年3月,这一功能只在三种浏览器(Chrome、Edge、Opera)上支持,即使在那些浏览器上也被归类为实验功能。
参见API文档:https://developer.mozilla.org/en-US/docs/Web/API/Window/showOpenFilePicker

相关问题