简体   繁体   English

在jQuery中模拟文件上载单击

[英]Emulate a file upload click in jQuery

I have an <img ... /> tag that I have bound a click event to in jQuery. 我有一个<img ... />标签,我已经在jQuery中绑定了一个click事件。 When it is clicked I'd like to have it emulate the click of a button on the file upload to open the file system browse pop-up. 单击它时,我想让它模拟文件上传中的按钮单击以打开文件系统浏览弹出窗口。 I've tried these things within the click function and had no success: 我在点击功能中尝试过这些东西并没有成功:

...
$(".hiddenUploadBtn").click();
...

...
$(".hiddenUploadBtn").select();
...

...
$(".hiddenUploadBtn").submit();
...

Just wrap the img in a label and set the for attribute to the file input. 只需将img包装在标签中,然后将for属性设置为文件输入。 Works for any kind of content and it's built into the spec. 适用于任何类型的内容,它内置于规范中。 You can even hide the file input at that point. 您甚至可以隐藏该点的文件输入。

<input type="file" id="fileUpload"><br>
<label for="fileUpload">
    <img src="https://www.google.com/images/srpr/logo11w.png" />
</label>

This works for me 这适合我

<input name="picture" type="file" onchange="alert(this.value)" class="file" size=20/>

for use upload button as image try this 使用上传按钮作为图像试试这个

<style>
div.fileinputs {position:relative; display:inline;}
div.fakefile {position:absolute; top:0px; left:0px; z-index:1;}
input.file {position:relative; text-align:right; -moz-opacity:0; filter:alpha(opacity: 0); opacity: 0; z-index:2;}
<style>

<div class="fileinputs">
  <input name="picture" type="file" onchange="alert(this.value)" class="file" size=1/>
  <div class="fakefile">
    <img src="images/browse.gif" align="middle" alt="browse" title="browse"/>
  </div>
</div>

so the input field is hidden, and when u click image - the selection dialog appears, but emulate this dialog from js imposible, yep. 所以输入字段是隐藏的,当你点击图像时 - 会出现选择对话框,但是从js imposible模仿这个对话框,是的。 But you can also write the plugin/hack for browser) 但你也可以为浏览器编写插件/ hack)

The spec says it is supposed to work, and it does, on Chrome. 规范说它应该可以在Chrome上运行,而且确实可行。 However, Firefox and other common browsers don't follow the rules, so you're SOL. 但是,Firefox和其他常见浏览器不遵守规则,所以你是SOL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM