Javascript 带有 jQuery 的 HTML 文件选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10997263/
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
Html file picker with jQuery
提问by hakan
Possible Duplicate:
Reading client side text file using Javascript
可能的重复:
使用 Javascript 读取客户端文本文件
I want to open a txt file at client, parse it with javascript and post parsed data to a server page with ajax. I have scripts for parsing and posting. All i need now is to simply pick file from client computer.
我想在客户端打开一个txt文件,用javascript解析它并用ajax将解析的数据发布到服务器页面。我有用于解析和发布的脚本。我现在需要的只是从客户端计算机中选择文件。
What I need is something like this:
我需要的是这样的:
<div id="content">
<button id="selectFile" onclick="return selectFileClick();" />
</div>
When user clicks button, a file dialog box appears and returns selected file. With this file name, I will make other operations like parsing etc.
当用户单击按钮时,会出现一个文件对话框并返回选定的文件。使用这个文件名,我将进行其他操作,如解析等。
function selectFileClick()
{
var fileName = filedialog();
// parsing file...
return false;
}
Edit: I dont want to upload file and I have a custom design which doesnt look like;
编辑:我不想上传文件,我有一个看起来不像的自定义设计;
<input type="file" id="file">
I need something like this: jquery file dialog plugin
我需要这样的东西:jquery file dialog plugin
Edit (2): I solved issue by this way;
编辑(2):我通过这种方式解决了问题;
$(function () {
$("#button1").click(function (event) {
event.preventDefault();
$('#file').trigger('click');
});
document.getElementById('file').addEventListener('change', readFile, false);
});
at html;
在 html;
<input id="button1" type="submit" value="add" />
<input type="file" id="file" style="display: none">
I hope this helps someone else ;)
我希望这对其他人有帮助;)
回答by phenomnomnominal
Have a look at this: HTML File API
看看这个:HTML File API
That would probably be the easiest way to do it, e.g.
这可能是最简单的方法,例如
<input type="file" id="file">
Then just attach a function to the "onChange" function of the element.
然后只需将一个函数附加到元素的“onChange”函数。
EDIT: Just noticed that you're using jQuery, so you could really just do:
编辑:刚刚注意到你正在使用 jQuery,所以你真的可以这样做:
$("#file").change(function() { selectFileClick(); });