Reputation: 149
I am adding file import functionality to an existing page.
I want to do this using javascript and without modifying the page, ie. without adding the "input type="file" " tag, everyone seems to be talking about.
I have added the button, now I want the event to show the file dialog, user to browse for file and javascript to submit file to server for validation.
How do I do that? Btw, main priority is opening file dialog, so no need for user or submitting part, if you don't know it.
Thx
Upvotes: 10
Views: 20924
Reputation:
Well, if I understand correct what you want, is some like this...
<input type="button" value="Add File" onclick="document.getElementById('file').click()" />
<input type="file" id="file" style="display:none" />
Hidding the file
object and calling the file dialog with another object. Right ?
EDIT: Only Javascript
myClickHandler() {
var f = document.createElement('input');
f.style.display='none';
f.type='file';
f.name='file';
document.getElementById('yourformhere').appendChild(f);
f.click();
}
button.onclick = myClickHandler
Put this in your object with the id
of your form
in place of yourformhere
!!
Upvotes: 11
Reputation: 51
Works for me:
export function pickFile(onFilePicked: (file: File) => void): void {
const inputElemenet = document.createElement('input');
inputElemenet.style.display = 'none';
inputElemenet.type = 'file';
inputElemenet.addEventListener('change', () => {
if (inputElemenet.files) {
onFilePicked(inputElemenet.files[0]);
}
});
const teardown = () => {
document.body.removeEventListener('focus', teardown, true);
setTimeout(() => {
document.body.removeChild(inputElemenet);
}, 1000);
}
document.body.addEventListener('focus', teardown, true);
document.body.appendChild(inputElemenet);
inputElemenet.click();
}
And then:
pickFile((file: File) => {
console.log(file);
})
Upvotes: 1
Reputation: 1751
Here's is a way of doing it without any Javascript and it's also compatible with every browser, including mobile.
BTW, in Safari, the input
gets disabled when hidden with display: none
. A better approach would be to use 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 for
in the label
pointing to the id
of the input like this:
<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">
Upvotes: 2
Reputation: 588
I hid my first button like this
<input style="display:none;" type="file" id="file" name="file"/>
The following triggers the input file:
<i class="fa fa-camera-retro fa-3x" type="button" data-toggle="tooltip" title="Escoje tu foto de perfil" id="secondbutton" ></i>
(i used an icon)
Which triggers my second button:
$( "#secondbutton" ).click(function() {
$( "#file" ).click();
});
From http://api.jquery.com/click/
Upvotes: -1