如何使用javascript打开文件/浏览对话框?

时间:2021-10-21 14:31:20

Is there any way to open the browse for files dialog box when a <a href> link is clicked using javascript? It should function like a normal browse for files button and give the names/list of files selected in response.

当使用javascript单击链接时,是否有办法打开文件浏览对话框?它应该像普通的文件浏览按钮一样运行,并给出响应中选择的文件的名称/列表。

9 个解决方案

#1


52  

Here is a non-jQuery solution. Note you can't just use .click() as some browsers do not support it.

这是一个非jquery解决方案。注意,不能只使用.click(),因为有些浏览器不支持。

<script type="text/javascript">
function performClick(elemId) {
   var elem = document.getElementById(elemId);
   if(elem && document.createEvent) {
      var evt = document.createEvent("MouseEvents");
      evt.initEvent("click", true, false);
      elem.dispatchEvent(evt);
   }
}
</script>
<a href="#" onclick="performClick('theFile');">Open file dialog</a>
<input type="file" id="theFile" />

#2


16  

Use this.

用这个。

<script>
  function openFileOption()
{
  document.getElementById("file1").click();
}
</script>
     <input type="file" id="file1" style="display:none">
     <a href="#" onclick="openFileOption();return;">open File Dialog</a>

#3


10  

Unfortunately, there isn't a good way to browse for files with a JavaScript API. Fortunately, it's easy to create a file input in JavaScript, bind an event handler to its change event, and simulate a user clicking on it. We can do this without modifications to the page itself:

不幸的是,使用JavaScript API浏览文件并不是一种好方法。幸运的是,很容易在JavaScript中创建文件输入、将事件处理程序绑定到其更改事件并模拟用户单击该事件。我们可以在不修改页面本身的情况下这样做:

$('<input type="file" multiple>').on('change', function () {
  console.log(this.files);
}).click();

this.files on the second line is an array that contains filename, timestamps, size, and type.

这一点。第二行上的文件是一个包含文件名、时间戳、大小和类型的数组。

#4


9  

Here's is a way of doing it without any Javascript and it's also compatible with any browser.

这是一种不用任何Javascript就能完成的方法,而且它也可以兼容任何浏览器。


EDIT: In Safari, the input gets disabled when hidden with display: none. A better approach would be to use position: fixed; top: -100em.

编辑:在Safari中,当使用display: none隐藏时,输入被禁用。一个更好的方法是使用位置:固定;上图:-100 em。


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

Also, if you prefer you can go the "correct way" by using for in the label pointing to the id of the input like this:

另外,如果你喜欢你可以用“正确的方式”,在标签中使用这样的输入的id:

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

#5


7  

Create input element.

Missing from these answers is how to get a file dialog without a input element on the page.

这些答案中缺少的是如何在页面上没有输入元素的情况下获取文件对话框。

The function to show the input file dialog.

显示输入文件对话框的函数。

function openFileDialog (accept, callback) {  // this function must be called from  a user
                                              // activation event (ie an onclick event)

    // Create an input element
    var inputElement = document.createElement("input");

    // Set its type to file
    inputElement.type = "file";

    // Set accept to the file types you want the user to select. 
    // Include both the file extension and the mime type
    inputElement.accept = accept;

    // set onchange event to call callback when user has selected file
    inputElement.addEventListener("change", callback)

    // dispatch a click event to open the file dialog
    inputElement.dispatchEvent(new MouseEvent("click")); 
}

NOTE the function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.

注意,该函数必须是用户激活(如单击事件)的一部分。尝试在没有用户激活的情况下打开文件对话框将失败。

NOTE input.accept is not used in Edge

注意输入。接受不是用在边缘。

Example.

Calling above function when user clicks an anchor element.

当用户单击锚点元素时调用上面的函数。

// wait for window to load
window.addEventListener("load", windowLoad);

// open a dialog function
function openFileDialog (accept, multy = false, callback) { 
    var inputElement = document.createElement("input");
    inputElement.type = "file";
    inputElement.accept = accept; // Note Edge does not support this attribute
    if (multy) {
        inputElement.multiple = multy;
    }
    if (typeof callback === "function") {
         inputElement.addEventListener("change", callback);
    }
    inputElement.dispatchEvent(new MouseEvent("click")); 
}

// onload event
function windowLoad () {
    // add user click event to userbutton
    userButton.addEventListener("click", openDialogClick);
}

// userButton click event
function openDialogClick () {
    // open file dialog for text files
    openFileDialog(".txt,text/plain", true, fileDialogChanged);
}

// file dialog onchange event handler
function fileDialogChanged (event) {
    [...this.files].forEach(file => {
        var div = document.createElement("div");
        div.className = "fileList common";
        div.textContent = file.name;
        userSelectedFiles.appendChild(div);
    });
}
.common {
    font-family: sans-serif;
    padding: 2px;
    margin : 2px;
    border-radius: 4px;
 }
.fileList {
    background: #229;
    color: white;
}
#userButton {
    background: #999;
    color: #000;
    width: 8em;
    text-align: center;
    cursor: pointer;
}

#userButton:hover {
   background : #4A4;
   color : white;
}
<a id = "userButton" class = "common" title = "Click to open file selection dialog">Open file dialog</a>
<div id = "userSelectedFiles" class = "common"></div>

Warning the above snippet is written in ES6.

警告上面的代码片段是用ES6编写的。

#6


1  

you can't use input.click() directly, but you can call this in other element click event.

不能直接使用input.click(),但可以在其他元素单击事件中调用它。

var a = document.querySelector('a');
var inpupt = document.querySelector('a');
a.addEventListener('click', function (e) {
    input.click();
});

this tell you Using hidden file input elements using the click() method

它告诉您使用隐藏的文件输入元素使用click()方法

#7


0  

I know this is an old post, but another simple option is using the INPUT TYPE="FILE" tag according to compatibility most major browser support this feature.

我知道这是一篇老文章,但另一个简单的选项是根据兼容性使用INPUT TYPE="FILE"标签大多数主流浏览器都支持这个特性。

#8


0  

I worked it around through this "hiding" div ...

我通过这个“隐藏”div…

<div STYLE="position:absolute;display:none;"><INPUT type='file' id='file1' name='files[]'></div>

#9


0  

How about make clicking the a tag, to click on the file button?

如何点击一个标签,点击文件按钮?

There is more browser support for this, but I use ES6, so if you really want to make it work in older and any browser, try to transpile it using babel, or just simply use ES5:

对此有更多的浏览器支持,但我使用ES6,所以如果你真的想让它在更老的浏览器和任何浏览器中工作,试着用babel将它转译过来,或者只是简单地使用ES5:

const aTag = document.getElementById("open-file-uploader");
const fileInput = document.getElementById("input-button");
aTag.addEventListener("click", () => fileInput.click());
#input-button {
  position: abosulte;
  width: 1px;
  height: 1px;
  clip: rect(1px 1px 1px 1px);
  clip: rect(1px, 1px, 1px, 1px);
}
<a href="#" id="open-file-uploader">Open file uploader</a>
<input type="file" id="input-button" />

#1


52  

Here is a non-jQuery solution. Note you can't just use .click() as some browsers do not support it.

这是一个非jquery解决方案。注意,不能只使用.click(),因为有些浏览器不支持。

<script type="text/javascript">
function performClick(elemId) {
   var elem = document.getElementById(elemId);
   if(elem && document.createEvent) {
      var evt = document.createEvent("MouseEvents");
      evt.initEvent("click", true, false);
      elem.dispatchEvent(evt);
   }
}
</script>
<a href="#" onclick="performClick('theFile');">Open file dialog</a>
<input type="file" id="theFile" />

#2


16  

Use this.

用这个。

<script>
  function openFileOption()
{
  document.getElementById("file1").click();
}
</script>
     <input type="file" id="file1" style="display:none">
     <a href="#" onclick="openFileOption();return;">open File Dialog</a>

#3


10  

Unfortunately, there isn't a good way to browse for files with a JavaScript API. Fortunately, it's easy to create a file input in JavaScript, bind an event handler to its change event, and simulate a user clicking on it. We can do this without modifications to the page itself:

不幸的是,使用JavaScript API浏览文件并不是一种好方法。幸运的是,很容易在JavaScript中创建文件输入、将事件处理程序绑定到其更改事件并模拟用户单击该事件。我们可以在不修改页面本身的情况下这样做:

$('<input type="file" multiple>').on('change', function () {
  console.log(this.files);
}).click();

this.files on the second line is an array that contains filename, timestamps, size, and type.

这一点。第二行上的文件是一个包含文件名、时间戳、大小和类型的数组。

#4


9  

Here's is a way of doing it without any Javascript and it's also compatible with any browser.

这是一种不用任何Javascript就能完成的方法,而且它也可以兼容任何浏览器。


EDIT: In Safari, the input gets disabled when hidden with display: none. A better approach would be to use position: fixed; top: -100em.

编辑:在Safari中,当使用display: none隐藏时,输入被禁用。一个更好的方法是使用位置:固定;上图:-100 em。


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

Also, if you prefer you can go the "correct way" by using for in the label pointing to the id of the input like this:

另外,如果你喜欢你可以用“正确的方式”,在标签中使用这样的输入的id:

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

#5


7  

Create input element.

Missing from these answers is how to get a file dialog without a input element on the page.

这些答案中缺少的是如何在页面上没有输入元素的情况下获取文件对话框。

The function to show the input file dialog.

显示输入文件对话框的函数。

function openFileDialog (accept, callback) {  // this function must be called from  a user
                                              // activation event (ie an onclick event)

    // Create an input element
    var inputElement = document.createElement("input");

    // Set its type to file
    inputElement.type = "file";

    // Set accept to the file types you want the user to select. 
    // Include both the file extension and the mime type
    inputElement.accept = accept;

    // set onchange event to call callback when user has selected file
    inputElement.addEventListener("change", callback)

    // dispatch a click event to open the file dialog
    inputElement.dispatchEvent(new MouseEvent("click")); 
}

NOTE the function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.

注意,该函数必须是用户激活(如单击事件)的一部分。尝试在没有用户激活的情况下打开文件对话框将失败。

NOTE input.accept is not used in Edge

注意输入。接受不是用在边缘。

Example.

Calling above function when user clicks an anchor element.

当用户单击锚点元素时调用上面的函数。

// wait for window to load
window.addEventListener("load", windowLoad);

// open a dialog function
function openFileDialog (accept, multy = false, callback) { 
    var inputElement = document.createElement("input");
    inputElement.type = "file";
    inputElement.accept = accept; // Note Edge does not support this attribute
    if (multy) {
        inputElement.multiple = multy;
    }
    if (typeof callback === "function") {
         inputElement.addEventListener("change", callback);
    }
    inputElement.dispatchEvent(new MouseEvent("click")); 
}

// onload event
function windowLoad () {
    // add user click event to userbutton
    userButton.addEventListener("click", openDialogClick);
}

// userButton click event
function openDialogClick () {
    // open file dialog for text files
    openFileDialog(".txt,text/plain", true, fileDialogChanged);
}

// file dialog onchange event handler
function fileDialogChanged (event) {
    [...this.files].forEach(file => {
        var div = document.createElement("div");
        div.className = "fileList common";
        div.textContent = file.name;
        userSelectedFiles.appendChild(div);
    });
}
.common {
    font-family: sans-serif;
    padding: 2px;
    margin : 2px;
    border-radius: 4px;
 }
.fileList {
    background: #229;
    color: white;
}
#userButton {
    background: #999;
    color: #000;
    width: 8em;
    text-align: center;
    cursor: pointer;
}

#userButton:hover {
   background : #4A4;
   color : white;
}
<a id = "userButton" class = "common" title = "Click to open file selection dialog">Open file dialog</a>
<div id = "userSelectedFiles" class = "common"></div>

Warning the above snippet is written in ES6.

警告上面的代码片段是用ES6编写的。

#6


1  

you can't use input.click() directly, but you can call this in other element click event.

不能直接使用input.click(),但可以在其他元素单击事件中调用它。

var a = document.querySelector('a');
var inpupt = document.querySelector('a');
a.addEventListener('click', function (e) {
    input.click();
});

this tell you Using hidden file input elements using the click() method

它告诉您使用隐藏的文件输入元素使用click()方法

#7


0  

I know this is an old post, but another simple option is using the INPUT TYPE="FILE" tag according to compatibility most major browser support this feature.

我知道这是一篇老文章,但另一个简单的选项是根据兼容性使用INPUT TYPE="FILE"标签大多数主流浏览器都支持这个特性。

#8


0  

I worked it around through this "hiding" div ...

我通过这个“隐藏”div…

<div STYLE="position:absolute;display:none;"><INPUT type='file' id='file1' name='files[]'></div>

#9


0  

How about make clicking the a tag, to click on the file button?

如何点击一个标签,点击文件按钮?

There is more browser support for this, but I use ES6, so if you really want to make it work in older and any browser, try to transpile it using babel, or just simply use ES5:

对此有更多的浏览器支持,但我使用ES6,所以如果你真的想让它在更老的浏览器和任何浏览器中工作,试着用babel将它转译过来,或者只是简单地使用ES5:

const aTag = document.getElementById("open-file-uploader");
const fileInput = document.getElementById("input-button");
aTag.addEventListener("click", () => fileInput.click());
#input-button {
  position: abosulte;
  width: 1px;
  height: 1px;
  clip: rect(1px 1px 1px 1px);
  clip: rect(1px, 1px, 1px, 1px);
}
<a href="#" id="open-file-uploader">Open file uploader</a>
<input type="file" id="input-button" />