$('#id').click();
它不适用于 Mac OS 上的 Chrome 26。
问题实际上是创建可以集成到表单中的“上传”小部件。 Widget 将由两部分组成。第一部分是带有启动器按钮和错误/成功消息的 div。 我认为方法是将另一个表单作为文件输入的第二部分并将文件提交到 iframe 中。提交后,我们在主表单的第一部分填写隐藏字段或在其中显示错误。
简单的方法是将文件表单添加到主表单中,但这是被禁止的。
最佳答案
仅 JS - 不需要 jquery
只需创建一个输入元素并触发点击。
var input = document.createElement('input');
input.type = 'file';
input.click();
这是最基本的,弹出一个选择文件对话框,但如果不处理所选文件,它就没有任何用处...
处理文件
向新创建的输入添加一个 onchange
事件将允许我们在用户选择文件后执行操作。
var input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
var file = e.target.files[0];
}
input.click();
目前我们有存储各种信息的文件变量:
file.name // the file's name including extension
file.size // the size in bytes
file.type // file type ex. 'application/pdf'
太棒了!
但是,如果我们需要文件的内容怎么办?
为了得到文件的实际内容,出于各种原因。放置图像、加载到 Canvas 、创建带有 Base64 数据 url 的窗口等。我们需要使用 FileReader
API
我们将创建 FileReader 的一个实例,并将用户选择的文件引用加载到它。
var input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
// getting a hold of the file reference
var file = e.target.files[0];
// setting up the reader
var reader = new FileReader();
reader.readAsText(file,'UTF-8');
// here we tell the reader what to do when it's done reading...
reader.onload = readerEvent => {
var content = readerEvent.target.result; // this is the content!
console.log( content );
}
}
input.click();
尝试将上面的代码粘贴到您的开发工具的控制台窗口中,它应该会产生一个选择文件对话框,在选择文件后,控制台现在应该会打印文件的内容。
示例 - “Stackoverflow 的新背景图片!”
让我们尝试创建一个文件选择对话框来将 stackoverflows 背景图像更改为更辣的东西......
var input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
// getting a hold of the file reference
var file = e.target.files[0];
// setting up the reader
var reader = new FileReader();
reader.readAsDataURL(file); // this is reading as data url
// here we tell the reader what to do when it's done reading...
reader.onload = readerEvent => {
var content = readerEvent.target.result; // this is the content!
document.querySelector('#content').style.backgroundImage = 'url('+ content +')';
}
}
input.click();
打开 devtools,并将上面的代码粘贴到控制台窗口中,这应该会弹出一个选择文件对话框,在选择图像时,stackoverflows 内容框背景应该更改为所选图像。
干杯!
关于javascript - 如何通过js打开选择文件对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16215771/