Javascript 以编程方式触发“选择文件”对话框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8595389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:38:35  来源:igfitidea点击:

Programmatically trigger "select file" dialog box

javascriptjqueryhtml

提问by tamakisquare

I have a hidden file input element. Is it possible to trigger its select filedialog box from a button's click event?

我有一个隐藏的文件输入元素。是否可以从按钮的单击事件触发其选择文件对话框?

回答by Mike Gwilt

If you're looking to have your own button to upload a file instead of using <input type="file" />, you can do something like:

如果您希望拥有自己的按钮来上传文件而不是使用<input type="file" />,您可以执行以下操作:

<input id="myInput" type="file" style="visibility:hidden" />
<input type="button" value="Show Dialog" onclick="$('#myInput').click();" />

Note that I used visibility: hidden, instead of display: none. You cannot call the click event on a non-displayed file input.

请注意,我使用visibility: hidden, 而不是display: none. 您不能在未显示的文件输入上调用 click 事件。

回答by Fazi

Most answers here are lacking a useful information:

这里的大多数答案都缺乏有用的信息:

Yes, you can programmatically click the input element using jQuery/JavaScript, but only if you do it in an event handler belonging to an event THAT WAS STARTED BY THE USER!

是的,您可以使用 jQuery/JavaScript 以编程方式单击输入元素,但前提是您在属于用户启动的事件的事件处理程序中执行此操作!

So, for example, nothing will happen if you, the script, programmatically click the button in an ajax callback, but if you put the same line of code in an event handler that was raised by the user, it will work.

因此,例如,如果脚本以编程方式单击 ajax 回调中的按钮,则不会发生任何事情,但是如果将同一行代码放入用户引发的事件处理程序中,它将起作用。

P.S. The debugger;keyword disrupts the browse window if it is before the programmatical click ...at least in chrome 33...

PSdebugger;如果在以编程方式单击之前,关键字会破坏浏览窗口...至少在 chrome 33 中...

回答by m_x

Just for the record, there is an alternative solution that does not require javascript. It is a bit of a hack, exploiting the fact that clicking on a label sets the focus on the associated input.

只是为了记录,有一个不需要 javascript 的替代解决方案。这有点像黑客,利用点击标签将焦点设置在相关输入上的事实。

You need a <label>with a proper forattribute (points to the input), optionnaly styled like a button (with bootstrap, use btn btn-default). When the user clicks the label, the dialog opens, example :

你需要一个<label>具有适当for属性(指向输入),可选样式像一个按钮(使用引导程序,使用btn btn-default)。当用户单击标签时,将打开对话框,例如:

<!-- optionnal, to add a bit of style -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

<!-- minimal setup -->
<label for="exampleInput" class="btn btn-default">
  Click me
</label>
<input type="file" id="exampleInput" style="display: none" />

回答by Bojangles

I'm not sure how browsers handle clicks on type="file"elements (security concerns and all), but this should work:

我不确定浏览器如何处理对type="file"元素的点击(安全问题和所有),但这应该有效:

$('input[type="file"]').click();

I've tested this JSFiddlein Chrome, Firefox and Opera and they all show the file browse dialog.

我已经在 Chrome、Firefox 和 Opera 中测试了这个 JSFiddle,它们都显示了文件浏览对话框。

回答by Ponyboy

I wrap the input[type=file]in a label tag, then style the labelto your liking, and hide the input.

我将 包裹input[type=file]在标签标签中,然后label根据您的喜好设置样式,并隐藏input.

<label class="btn btn-default fileLabel" data-toggle="tooltip" data-placement="top" title="Upload">
    <input type="file">
    <span><i class="fa fa-upload"></i></span>
</label>

<style>
    .fileLabel input[type="file"] {
        position: fixed;
        top: -1000px;
    }
</style>

Purely CSS Solution.

纯 CSS 解决方案。

回答by Alister

Natively the only way is by creating an <input type="file">element and then simulating a click, unfortunately.

不幸的是,本地唯一的方法是创建一个<input type="file">元素然后模拟点击。

There's a tiny plugin (shameless plug) which will take the pain away of having to do this all the time: file-dialog

有一个小插件(无耻插件)可以消除必须一直这样做的痛苦:文件对话框

fileDialog()
    .then(file => {
        const data = new FormData()
        data.append('file', file[0])
        data.append('imageName', 'flower')

        // Post to server
        fetch('/uploadImage', {
            method: 'POST',
            body: data
        })
    })

回答by Pessa

The best solution, works in all browsers.. even on mobile.

最好的解决方案,适用于所有浏览器......甚至在移动设备上。

<div class="btn" id="s_photo">Upload</div>

<input type="file" name="s_file" id="s_file" style="opacity: 0;">';

<!--jquery-->

<script>
    $("#s_photo").click(function() {
        $("#s_file").trigger("click");
    });
</script>

Hiding the input file type causes problems with browsers, opacity is the best solution because it isn't hiding, just not showing. :)

隐藏输入文件类型会导致浏览器出现问题,不透明度是最好的解决方案,因为它不是隐藏,只是不显示。:)

回答by Alex Turpin

There is no cross browser way of doing it, for security reasons. What people usually do is overlay the input file over something else and set it's visibility to hidden so it gets triggered on it's own. More info here.

出于安全原因,没有跨浏览器的方式来做到这一点。人们通常做的是将输入文件覆盖在其他内容上,并将其可见性设置为隐藏,以便它自己触发。更多信息在这里。

回答by m-farhan

Make sure you are using binding to get component props in REACT

确保您正在使用绑定来获取 REACT 中的组件道具

class FileUploader extends Component {
  constructor (props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
   onChange=(e,props)=>{
    const files = e.target.files;
    const selectedFile = files[0];
    ProcessFileUpload(selectedFile,props.ProgressCallBack,props.ErrorCallBack,props.CompleatedCallBack,props.BaseURL,props.Location,props.FilesAllowed);
  }
   handleClick = () => {
    this.refs.fileUploader.click();
  }
  render()
  {
  return(
      <div>
        <button type="button" onClick={this.handleClick}>Select File</button>  
        <input type='file' onChange={(e)=>this.onChange(e,this.props)} ref="fileUploader" style={{display:"none"}} />
      </div>)
  }
}

回答by Vinicius Lima

For those who want the same but are using React

对于那些想要相同但正在使用 React 的人

openFileInput = () => {
    this.fileInput.click()
}


<a href="#" onClick={this.openFileInput}>
    <p>Carregue sua foto de perfil</p>
    <img src={img} />
</a>
<input style={{display:'none'}} ref={(input) => { this.fileInput = input; }} type="file"/>