Can an HTML button be used to upload a file for use with the W3C File API?
I have a thumbnail interface mockup, and I would like to add the ability to upload an image. According to my mockup, the interface looks like this:
The intent was that the user would click on the "Add Icon" button, and a file dialog would pop up, just like the one that pops up when a file input is clicked. I would like the use the W3C's File API to handle the file upload asynchronously, and display the thumbnail in the gray area above the button once the upload is complete.
So, I'd like to upload a file without using a file input HTML element. I tried working with a hidden file input element and calling its click
event handler with Javascript when the "Add Icon" button is clicked, but the call didn't do开发者_如何学JAVA anything. I think security might have some reason to do with this.
Has anyone had any luck using an HTML button
to upload a file before?
The trick I always do is wrapping the hidden file input
into a label
tag and then putting my custom input
elements in the label
tag. By defenition clicking on anything inside the label
tag should trigger the input
inside. No JavaScript needed at all!
<label>
<div>
My custom file input
</div>
<input type="file" id="file"/>
</label>
CSS: input{visibility:hidden;}
Please note that you can't use display:none
because then the element will not render. Still you can make the element width:0; height:0;
to hide input
element completely.
Fiddle
Using HTML file API is a little different. Read this article at Mozilla Developer Network to leran more.
精彩评论