来自 JavaScript *without* <input> 的文件对话框

2022-01-15 00:00:00 file dialog javascript

我正在向现有页面添加文件导入功能.

I am adding file import functionality to an existing page.

我想使用 javascript 并且不修改页面来执行此操作,即.不加input type="file""标签,大家好像都在议论纷纷.

I want to do this using javascript and without modifying the page, ie. without adding the "input type="file" " tag, everyone seems to be talking about.

我已经添加了按钮,现在我希望事件显示文件对话框,用户浏览文件和 javascript 提交文件到服务器进行验证.

I have added the button, now I want the event to show the file dialog, user to browse for file and javascript to submit file to server for validation.

我该怎么做?顺便说一句,主要优先级是打开文件对话框,所以不需要用户或提交部分,如果你不知道的话.

How do I do that? Btw, main priority is opening file dialog, so no need for user or submitting part, if you don't know it.

谢谢

推荐答案

好吧,如果我理解正确你想要什么,是这样的......

Well, if I understand correct what you want, is some like this...

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

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

Hidding the file object and calling the file dialog with another object. Right ?

仅 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

formid 代替 yourformhere 将其放入对象中!!

Put this in your object with the id of your form in place of yourformhere !!

相关文章