javascript 使用jQuery打开文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22255071/
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
open file using jQuery
提问by Benson
I try to open a file using jQuery. Here is my HTML,
我尝试使用 jQuery 打开一个文件。这是我的 HTML,
<button onclick='load();'>load</button>
Here is my js code:
这是我的js代码:
function load() {
var fileSelector = $('<input id="load" type = "file" multiple />');
fileSelector.click();
//code here to get the files ...
}
Now I want to get the loaded files, what should I do?
现在我想获取加载的文件,我该怎么做?
回答by Leonardo Delfino
The HTML5 File Api (http://dev.w3.org/2006/webapi/FileAPI/) allows opening files, however the files must be selected by the User for security.
HTML5 文件 Api ( http://dev.w3.org/2006/webapi/FileAPI/) 允许打开文件,但是为了安全起见,用户必须选择这些文件。
If you need to open a file without user interaction, then it is necessary to do this on the server side with a language like PHP for example.
如果您需要在没有用户交互的情况下打开文件,则有必要在服务器端使用 PHP 等语言执行此操作。
回答by John Kenneth larbo
Here's my solution I used the file type input and then use the Jquery trigger function to trigger the click event for file input.
这是我的解决方案,我使用文件类型输入,然后使用 Jquery 触发器函数触发文件输入的单击事件。
$(function(){
$("#btnFile").click(function(){
$("#file").trigger("click");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="file" type="file" hidden/>
<button id="btnFile">Click Me</button>