Jquery trigger file input

2018-12-31 10:15发布

Am trying to trigger an upload box (browse button) using jQuery.
The method I have tried now is:

$('#fileinput').trigger('click');   

But it doesn't seem to work. Please help. Thank you.

19条回答
牵手、夕阳
2楼-- · 2018-12-31 10:44

This is due to a security restriction.

I found out that the security restriction is only when the <input type="file"/> is set to display:none; or is visbilty:hidden.

So i tried positioning it outside the viewport by setting position:absolute and top:-100px; and voilà it works.

see http://jsfiddle.net/DSARd/1/

call it a hack.

Hope that works for you.

查看更多
何处买醉
3楼-- · 2018-12-31 10:44

I managed with a simple $(...).click(); with JQuery 1.6.1

查看更多
查无此人
4楼-- · 2018-12-31 10:44

This is probably the best answer, keeping in mind the cross browser issues.

CSS:

#file {
  opacity: 0;
  width: 1px;
  height: 1px;
}

JS:

$(".file-upload").on('click',function(){
   $("[name='file']").click();
});

HTML:

<a class="file-upload">Upload</a>
<input type="file" name="file">
查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 10:47

Check out my fiddle.

http://jsfiddle.net/mohany2712/vaw8k/

.uploadFile {
  visibility: hidden;
}

#uploadIcon {
  cursor: pointer;
}
<body>
  <div class="uploadBox">
    <label for="uploadFile" id="uploadIcon">
      <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Icon_-_upload_photo_2.svg/512px-Icon_-_upload_photo_2.svg.png"  width="20px" height="20px"/>
    </label>
    <input type="file" value="upload" id="uploadFile" class="uploadFile" />
  </div>
</body>

查看更多
ら面具成の殇う
6楼-- · 2018-12-31 10:49

I have it working (=tested) in IE8+, recent FF and chrome:

$('#uploadInput').focus().trigger('click');

The key is focusing before firing the click (otherwise chrome ignores it).

Note: you do NEED to have your input displayed and visible (as in, not display:none and not visibility:hidden). I suggest (as many other have before) to absolutely position the input and throw it off screen.

#uploadInput {
    position: absolute;
    left: -9999px;
}
查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 10:49

or else simply

$(':input[type="file"]').show().click().hide();
查看更多
登录 后发表回答