jQuery 如何通过js打开选择文件对话框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16215771/
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
How open select file dialog via js?
提问by Luciuz
$('#id').click();
It doesn't work on Chrome 26 on Mac OS =(
它不适用于 Mac OS 上的 Chrome 26 =(
The problem actually is creation "upload" widget that can be integrated in a form. Widget will consists of two parts. The first part is div with initiator button and error/success messages. I think the way is put another form as the second part with file input and submit file into the iframe. After submition we fill hidden field in first part in main form or show errors in the same.
问题实际上是创建可以集成到表单中的“上传”小部件。Widget 将由两部分组成。第一部分是带有启动器按钮和错误/成功消息的 div。我认为方法是将另一个表单作为文件输入的第二部分并将文件提交到 iframe 中。提交后,我们在主表单的第一部分填写隐藏字段或显示错误。
Easy way is adding file-form into main-form, but it's prohibited.
简单的方法是将文件表单添加到主表单中,但这是禁止的。
Fix me.
整我。
回答by Ron van der Heijden
Using jQuery
使用 jQuery
I would create a button and an invisible input like so
我会像这样创建一个按钮和一个不可见的输入
<button id="button">Open</button>
<input id="file-input" type="file" name="name" style="display: none;" />
and add some jQuery to trigger it:
并添加一些 jQuery 来触发它:
$('#button').on('click', function() {
$('#file-input').trigger('click');
});
Using Vanilla JS
使用香草 JS
Same idea, without jQuery (credits to @Pascale)
同样的想法,没有 jQuery(归功于@Pascale)
<button onclick="document.getElementById('file-input').click();">Open</button>
<input id="file-input" type="file" name="name" style="display: none;" />
回答by Ron van der Heijden
JS only - no need for jquery
仅 JS - 不需要 jquery
Simply create an input element and trigger the click.
只需创建一个输入元素并触发点击。
var input = document.createElement('input');
input.type = 'file';
input.click();
This is the most basic, pop a select-a-file dialog, but its no use for anything without handling the selected file...
这是最基本的,弹出一个选择文件对话框,但如果不处理所选文件,它就没有任何用处......
Handling the files
处理文件
Adding an onchange
event to the newly created input would allow us to do stuff once the user has selected the file.
onchange
一旦用户选择了文件,向新创建的输入添加一个事件将允许我们做一些事情。
var input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
var file = e.target.files[0];
}
input.click();
At the moment we have the file variable storing various information :
目前我们有存储各种信息的文件变量:
file.name // the file's name including extension
file.size // the size in bytes
file.type // file type ex. 'application/pdf'
Great!
伟大的!
But, what if we need the content of the file?
但是,如果我们需要文件的内容怎么办?
In order to get to the actual content of the file, for various reasons. place an image, load into canvas, create a window with Base64 data url, etc. we would need to use the FileReader
API
为了得到文件的实际内容,出于各种原因。放置图像、加载到画布、使用 Base64 数据 url 创建窗口等。我们需要使用FileReader
API
We would create an instance of the FileReader, and load our user selected file reference to it.
我们将创建 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();
Trying pasting the above code into your devtool's console window, it should produce a select-a-file dialog, after selecting the file, the console should now print the contents of the file.
尝试将上述代码粘贴到 devtool 的控制台窗口中,它应该会产生一个选择文件对话框,选择文件后,控制台现在应该打印文件的内容。
Example - "Stackoverflow's new background image!"
示例 - “Stackoverflow 的新背景图片!”
Let's try to create a file select dialog to change stackoverflows background image to something more spicy...
让我们尝试创建一个文件选择对话框来将 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();
open devtools, and paste the above code into console window, this should pop a select-a-file dialog, upon selecting an image, stackoverflows content box background should change to the image selected.
打开 devtools,并将上面的代码粘贴到控制台窗口中,这应该会弹出一个选择文件对话框,选择图像后,stackoverflows 内容框背景应更改为所选图像。
Cheers!
干杯!
回答by Pascale
For the sake of completeness, Ron van der Heijden's solutionin pure JavaScript:
为了完整起见,Ron van der Heijden 的纯 JavaScript解决方案:
<button onclick="document.querySelector('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">
回答by nunocastromartins
In HTML only:
仅在 HTML 中:
<label>
<input type="file" name="input-name" style="display: none;" />
<span>Select file</span>
</label>
Edit:I hadn't tested this in Blink, it actually doesn't work with a <button>
, but it should work with most other elements–at least in recent browsers.
编辑:我没有在 Blink 中测试过这个,它实际上不适用于<button>
,但它应该适用于大多数其他元素 - 至少在最近的浏览器中。
Check this fiddlewith the code above.
用上面的代码检查这个小提琴。
回答by Yairopro
READY TO USE FUNCTION (using Promise)
准备使用功能(使用 Promise)
/**
* Select file(s).
* @param {String} contentType The content type of files you wish to select. For instance "image/*" to select all kinds of images.
* @param {Boolean} multiple Indicates if the user can select multiples file.
* @returns {Promise<File|File[]>} A promise of a file or array of files in case the multiple parameter is true.
*/
function (contentType, multiple){
return new Promise(resolve => {
let input = document.createElement('input');
input.type = 'file';
input.multiple = multiple;
input.accept = contentType;
input.onchange = _ => {
let files = Array.from(input.files);
if (multiple)
resolve(files);
else
resolve(files[0]);
};
input.click();
});
}
TEST IT
测试它
// Content wrapper element
let contentElement = document.getElementById("content");
// Button callback
async function onButtonClicked(){
let files = await selectFile("image/*", true);
contentElement.innerHTML = files.map(file => `<img src="${URL.createObjectURL(file)}" style="width: 100px; height: 100px;">`).join('');
}
// ---- function definition ----
function selectFile (contentType, multiple){
return new Promise(resolve => {
let input = document.createElement('input');
input.type = 'file';
input.multiple = multiple;
input.accept = contentType;
input.onchange = _ => {
let files = Array.from(input.files);
if (multiple)
resolve(files);
else
resolve(files[0]);
};
input.click();
});
}
<button onclick="onButtonClicked()">Select images</button>
<div id="content"></div>
回答by Robert Kehoe
To expand on the answer from 'levi' and to show how to get the response from the upload so you can process the file upload:
扩展'levi'的答案并展示如何从上传中获取响应,以便您可以处理文件上传:
selectFile(event) {
event.preventDefault();
file_input = document.createElement('input');
file_input.addEventListener("change", uploadFile, false);
file_input.type = 'file';
file_input.click();
},
uploadFile() {
let dataArray = new FormData();
dataArray.append('file', file_input.files[0]);
// Obviously, you can substitute with JQuery or whatever
axios.post('/your_super_special_url', dataArray).then(function() {
//
});
}
回答by Hassaan Raza
First Declare a variable to store filenames(to use them later):
首先声明一个变量来存储文件名(稍后使用):
var myfiles = [];
Open File Dialog
打开文件对话框
$('#browseBtn').click(function() {
$('<input type="file" multiple>').on('change', function () {
myfiles = this.files; //save selected files to the array
console.log(myfiles); //show them on console
}).click();
});
i'm posting it, so it may help someone because there are no clear instructions on the internet to how to store filenames into an array!
我正在发布它,所以它可能对某人有所帮助,因为互联网上没有关于如何将文件名存储到数组中的明确说明!
回答by Arcanjo ZN
With jquery library
使用 jquery 库
<button onclick="$('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">