在 JavaScript 中打开文件对话框

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

Open file dialog box in JavaScript

javascriptfiledialog

提问by ArK

I need a solution to display open file dialog in HTML while clicking a div. The open file dialog box must open when the divis clicked.

我需要一个解决方案来在单击 .html 文件时以 HTML 显示打开文件对话框divdiv单击时必须打开打开文件对话框。

I don't want to display the input file box as part of HTML page. It must be displayed in separate dialog, which is not a part of the web page.

我不想将输入文件框显示为 HTML 页面的一部分。它必须显示在单独的对话框中,而不是网页的一部分。

采纳答案by rahul

Here is a nice one

这是一个不错的

Fine Uploader demo

精美的上传器演示

It is an <input type='file' />control itself. But a div is placed over that and css styles are applied to get that feel. Opacity of the file control is set to 0 so that it appears that the dialog window is opened when clicking on the div.

<input type='file' />本身就是一个控件。但是在它上面放置了一个 div 并应用了 css 样式来获得这种感觉。文件控件的不透明度设置为 0,以便在单击 div 时显示对话框窗口。

回答by Somwang Souksavatd

    $("#logo").css('opacity','0');
    
    $("#select_logo").click(function(e){
       e.preventDefault();
       $("#logo").trigger('click');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="select_logo">Select Logo</a> <input type="file" id="logo">

for IE add this:

对于 IE 添加这个:

$("#logo").css('filter','alpha(opacity = 0');

回答by JP de la Torre

I dont't know why nobody has pointed this out but 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>

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 Tigran Saluev

Actually, you don't need all that stuff with opacity, visibility, <input>styling, etc. Just take a look:

实际上,您不需要所有具有不透明度、可见性、<input>样式等的东西。只需看看:

<a href="#">Just click me.</a>
<script type="text/javascript">
    $("a").click(function() {
        // creating input on-the-fly
        var input = $(document.createElement("input"));
        input.attr("type", "file");
        // add onchange handler if you wish to get the file :)
        input.trigger("click"); // opening dialog
        return false; // avoiding navigation
    });
</script>

Demo on jsFiddle. Tested in Chrome 30.0 and Firefox 24.0. Didn't work in Opera 12.16, however.

jsFiddle 上的演示。在 Chrome 30.0 和 Firefox 24.0 中测试。但是,在 Opera 12.16 中不起作用。

回答by Chris

This is what worked best for me (Tested on IE8, FF, Chrome, Safari).

这是最适合我的方法(在 IE8、FF、Chrome、Safari 上测试)。

#file-input {
  cursor: pointer;
  outline: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  overflow: hidden;
  filter: alpha(opacity=0); /* IE < 9 */
  opacity: 0;
}
.input-label {
  cursor: pointer;
  position: relative;
  display: inline-block;
}
<label for="file-input" class="input-label">
  Click Me <!-- Replace with whatever text or icon you wish to use -->
  <input type="file" id="file-input">
</label>

Explanation:I positioned the file input directly above the element to be clicked, so any clicks would either land on it or its label (which pulls up the upload dialog just as if you clicked the label itself). I had some issues with the button part of the default input sticking out of the side of the label, so overflow: hiddenon the input and display: inline-blockon the label were necessary.

说明:我将文件输入直接放置在要单击的元素上方,因此任何单击都会落在它或其标签上(这会拉起上传对话框,就像您单击标签本身一样)。我在默认输入的按钮部分伸出标签侧面时遇到了一些问题,因此overflow: hidden需要输入和display: inline-block标签。

回答by Pratik

What if javascript is Turned Off on clients machine? Use following solution for all scenarios. You dont even need javascript/jQuery. :

如果 javascript 在客户端机器上关闭怎么办?对所有场景使用以下解决方案。你甚至不需要 javascript/jQuery。:

HTML

HTML

<label for="fileInput"><img src="File_upload_Img"><label>
<input type="file" id="fileInput"></label>

CSS

CSS

#fileInput{opacity:0}  
body{
    background:cadetblue;
}

Explanation : for="Your input Id". Triggers click event by default by HTML. So it by default triggers click event, no need of jQuery/javascript. If its simply done by HTML why use jQuery/jScript? And you cant tell if client disabled JS. Your feature should work even though JS is turned off.

解释:for="Your input Id"。默认情况下通过 HTML 触发单击事件。所以它默认触发点击事件,不需要 jQuery/javascript。如果它只是由 HTML 完成,为什么要使用 jQuery/jScript?而且您无法判断客户端是否禁用了 JS。即使关闭了 JS,您的功能也应该可以工作。

Working jsFiddle(You dont need JS , jquery)

工作 jsFiddle(你不需要 JS ,jquery)

回答by Pratik

First add in the headtags:

首先添加head标签:

<script>
   function showDialog(openFileDialog) {
       document.getElementById(openFileDialog).click();
   }
   function fileName(openFileDialog) {
       return document.getElementById(openFileDialog).value;
   }
   function hasFile(openFileDialog) {
       return document.getElementById(openFileDialog).value != "";
   }
   function fileNameWithoutFakePath(openFileDialog) {
       var fileName = document.getElementById(openFileDialog).value;
       return fileName.substr(fileName.lastIndexOf('\') + 1);
   }
   function fakePathWithoutFileName(openFileDialog) {
       var fileName = document.getElementById(openFileDialog).value;
       return fileName.substr(0, fileName.lastIndexOf('\'));
   }
</script>

if you already have scripttags, just add these functions above.

如果您已经有脚本标签,只需在上面添加这些功能。

In your bodyor formtags adding:

在您的正文表单标签中添加:

<input type="file" style="display:none" id="yourDesiredOrFavoriteNameForTheNewOpenFileDialogInstance"/>

No matter where in your html, is just like thatyou've created a new instance of type OpenFileDialog class as globalvariable, whose name is the idof the element, no matter where in your code or xaml, butin your script or code, you can'ttype his name, and then read a property or call a function, because there are global functions that do those that are not defined in the element input type="file". You just have to give these functions the id of the hidden input type="file" which is the name of the OpenFileDialog instance as string.

无论在您的 html 中的哪个位置,就像您创建了一个 OpenFileDialog 类型的新实例作为全局变量,其名称是元素的id,无论您在代码或 xaml 中的哪个位置,而是在您的脚本或代码中,你不能输入他的名字,然后读取一个属性或调用一个函数,因为有全局函数做那些在元素input type="file"中没有定义的。您只需要为这些函数提供隐藏输入类型 =“文件”的 id,即 OpenFileDialog 实例的名称作为字符串。

To ease your life in creating open file dialogs instances to your html, you can make a function that does it:

为了让您轻松地为 html 创建打开的文件对话框实例,您可以创建一个函数来执行此操作:

function createAndAddNewOpenFileDialog(name) {
     document.getElementById("yourBodyOrFormId").innerHtml += "<input type='file' style='display:none' id='" + name + "'/>"
}

and if you want to remove open file dialog, then you can make and use the following function:

如果要删除打开文件对话框,则可以创建并使用以下功能:

function removeOpenFileDialog(name) {
    var html = document.getElementById("yourBodyOrFormId").innerHtml;
    html = html.replace("<input type='file' style='display:none' id='" + name + "'/>", "");
    document.getElementById("yourBodyOrFormId").innerHtml = html;
}

but before you remove open file dialog, ensure that it exists by making and using the following function:

但在删除打开文件对话框之前,请通过创建和使用以下函数来确保它存在:

function doesOpenFileDialogExist(name) {
    return document.getElementById("yourBodyOrFormId").innerHtml.indexOf("<input type='file' style='display:none' id='" + name + "'/>") != -1
}

and if you don't want to create and add the open file dialogs in the bodyor formtags in the html, because this is adding hidden input type="file"s, then you can do it in script using the create function above:

如果您不想在正文中创建和添加打开文件对话框或在 html 中的表单标签中创建和添加打开的文件对话框,因为这是添加隐藏输入类型 =“文件”,那么您可以使用上面的创建函数在脚本中进行:

function yourBodyOrFormId_onload() {
    createAndAddNewOpenFileDialog("openFileDialog1");
    createAndAddNewOpenFileDialog("openFileDialog2");
    createAndAddNewOpenFileDialog("openFileDialog3");
    createAndAddNewOpenFileDialog("File Upload");
    createAndAddNewOpenFileDialog("Image Upload");
    createAndAddNewOpenFileDialog("bla");
    //etc and rest of your code
}

Ensure that near your body or form tags, you added:

确保在您的 body 或 form 标签附近,您添加了:

onload="yourBodyOrFormId_onload()"

You don't have to do this line above, if you did it already.

如果您已经这样做了,则不必执行上面的这一行。

TIP:You can add to your project or website new JScript File, if you don't have yet, and in this file you can put all the open file dialog functions away from the scripttags and the html or web form page, and use them in your html or web form page from this JScript file, but don't forget before to link the html or web form page to the JScript File of course. You can do it just by dragging the JScript file to your html page in the headtags. If your page is web form and not simple html, and you don't have head tags, then put it anywhere so that it can work. Don't forget to define global variable in that JScript File, whose value will be your body or form id as string. After you linked the JScript file to your html or web form page, you can onload event of your body of form, set the value of that variable to your body or form id. Then in the JScript File, you don't have to give to the document the id of the body or form of one page anymore, just give it the value of that variable. You can call that variable bodyIdor formIdor bodyOrFormIdor any other name you want.

提示:您可以将新的 JScript 文件添加到您的项目或网站中,如果您还没有,并且在此文件中您可以将所有打开文件对话框功能从脚本标签和 html 或 web 表单页面中删除,并使用从这个 JScript 文件将它们添加到您的 html 或 web 表单页面中,但不要忘记之前将 html 或 web 表单页面链接到 JScript 文件。您只需将 JScript 文件拖到头部的html 页面即可标签。如果您的页面是 web 表单而不是简单的 html,并且您没有 head 标签,那么将它放在任何地方,以便它可以工作。不要忘记在该 JScript 文件中定义全局变量,其值将是您的正文或表单 ID 作为字符串。将 JScript 文件链接到 html 或 web 表单页面后,您可以 onload 表单正文的事件,将该变量的值设置为您的正文或表单 ID。然后在 JScript 文件中,您不必再为文档提供正文或一页表单的 id,只需提供该变量的值即可。您可以调用该变量bodyIdformIdbodyOrFormId或您想要的任何其他名称。

Good luck man!

祝你好运!

回答by Karol Selak

The simplest way:

最简单的方法:

#file-input {
  display: none;
}
<label for="file-input">
  <div>Click this div and select a file</div>
</label>
<input type="file" id="file-input"/>

What's important, usage of display: noneensures that no place will be occupied by the hidden file input (what happens using opacity: 0).

重要的是,使用 ofdisplay: none确保隐藏文件输入不会占用任何地方(使用 会发生什么opacity: 0)。

回答by Dan F

AFAIK you still need an <input type="file">element, then you can use some of the stuff from quirksmodeto style it up

AFAIK 你仍然需要一个<input type="file">元素,然后你可以使用一些来自quirksmode的东西来设计它

回答by Martijn Laarman

The only without <input type="file">is by embedding a transparent flash movie over the div. You can then use a user generated click event (compliant with Flash 10 new security rules) to trigger a call to flash's FileReference.browse.

唯一没有的<input type="file">是通过在 div 上嵌入一个透明的 Flash 电影。然后,您可以使用用户生成的点击事件(符合 Flash 10 新安全规则)来触发对 Flash 的FileReference.browse的调用。

It offers an added dependency over the quirksmode waybut in return you get alot more events (such as built in progress events).

它提供了对quirksmode 方式的额外依赖,但作为回报,您会获得更多事件(例如内置进度事件)。