使用JavaScript创建文件对话框 *无需* <input> 元素

9
我正在为一个已有页面添加文件导入功能。
我希望使用JavaScript实现此功能,而不需要修改页面,也就是不需要添加“input type = file”标签,似乎每个人都在谈论这个。
我已经添加了按钮,现在我想要事件来显示文件对话框,用户浏览文件,然后使用JavaScript将文件提交到服务器进行验证。
我该怎么做? 顺便说一句,主要优先级是打开文件对话框,所以如果您不知道如何处理用户或提交部分,则无需考虑。
谢谢。
4个回答

10

嗯,如果我理解你的意思正确的话,你想要的是这样的...

<input type="button" value="Add File" onclick="document.getElementById('file').click()" />
<input type="file" id="file" style="display:none" />

隐藏file对象并使用另一个对象调用文件对话框。对吗?

编辑:仅限JavaScript

myClickHandler() {
    var f = document.createElement('input');
    f.style.display='none';
    f.type='file';
    f.name='file';
    document.getElementById('yourformhere').appendChild(f);
    f.click();
}

button.onclick = myClickHandler

将此代码放入你的对象中,用你表单的 id 替换 yourformhere !!

是的,类似于那样,但最好不用任何标签。我正在现有应用程序的基础上编码,目前不允许我太多更改站点。 - jvlarsen
DOM元素没有"click"方法。 - I.devries
2
谢谢。我以您的JavaScript为灵感,编写了以下代码: var element = document.createElement("input"); element.setAttribute("id", "importFile"); element.setAttribute("type", "file"); element.setAttribute("style", "visibility:hidden;"); 然后在调用方法中添加了点击事件,并实现了对话框弹出 :-) - jvlarsen
@I.devries 现在检查,我发现它在Chrome中根本不起作用。 - user898741

2

这里有一种无需任何Javascript的方法,而且兼容所有浏览器,包括移动端。


顺便说一下,在Safari中,使用display: none隐藏input会导致其被禁用。更好的方法是使用position: fixed; top: -100em


<label>
  Open file dialog
  <input type="file" style="position: fixed; top: -100em">
</label>

如果您愿意,可以按照“正确的方式”使用

<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">

1

对我来说可以运行:

export function pickFile(onFilePicked: (file: File) => void): void {
    const inputElemenet = document.createElement('input');
    inputElemenet.style.display = 'none';
    inputElemenet.type = 'file';

    inputElemenet.addEventListener('change', () => {
        if (inputElemenet.files) {
            onFilePicked(inputElemenet.files[0]);
        }
    });

    const teardown = () => {
        document.body.removeEventListener('focus', teardown, true);
        setTimeout(() => {
            document.body.removeChild(inputElemenet);
        }, 1000);
    }
    document.body.addEventListener('focus', teardown, true);

    document.body.appendChild(inputElemenet);
    inputElemenet.click();
}

然后:

pickFile((file: File) => {
    console.log(file);
})

-1
我是这样隐藏我的第一个按钮的:

<input style="display:none;" type="file" id="file" name="file"/>

以下代码触发输入文件:

<i class="fa fa-camera-retro fa-3x" type="button" data-toggle="tooltip" title="Escoje tu foto de perfil" id="secondbutton" ></i>(使用图标)

触发我的第二个按钮:
$( "#secondbutton" ).click(function() {
        $( "#file" ).click();
});

http://api.jquery.com/click/


1
仍然使用<input>。 - agilob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接