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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6463439/
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-23 21:52:44  来源:igfitidea点击:

How to open a file / browse dialog using javascript?

javascriptjquery

提问by Click Upvote

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.

<a href>使用javascript单击链接时,有没有办法打开浏览文件对话框?它应该像普通的文件浏览按钮一样起作用,并给出响应中选择的文件名称/列表。

回答by Samuel Liew

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" />

回答by birendra

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>

回答by Blindman67

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")); 
}

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

NOTEinput.acceptis not used in Edge

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

注意input.accept在 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>

Warningthe above snippet is written in ES6.

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

回答by Brad

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 changeevent, and simulate a user clicking on it. We can do this without modifications to the page itself:

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

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

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

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

回答by JP de la Torre

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

这是一种无需任何 Javascript 的方法,它也与任何浏览器兼容。



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

编辑:在 Safari 中,input使用display: none. 更好的方法是使用position: fixed; top: -100em.



<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 forin the labelpointing to the idof the input like this:

此外,如果您愿意,您可以通过在指向输入的 中使用“正确的方式”,如下所示:forlabelid

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

回答by xavierskip

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

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

html

html

<input type="file">
<button>Select file</button>

js

js

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

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

这告诉你使用 click() 方法使用隐藏文件输入元素

回答by Sandro Rosa

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

我通过这个“隐藏”的 div 解决了这个问题......

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

回答by Alireza

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

点击a 标签,点击文件按钮怎么样?

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" />

回答by JJ.

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" 标签,大多数主要浏览器都支持此功能。