Home > Mobile >  How to fill a input type="file" through only Javascript?
How to fill a input type="file" through only Javascript?

Time:12-08

I'm trying to fill a form and submit it using only JS.

For instance, in this page :

<form>
    <input id="yourname" type="text"></input><br/>
    <input id="yourfile" type="file"></input><br/>
    <input type="submit"></input><br/>
</form>

I'm trying to use something like this to submit the form :

document.getElementById('yourname').value = 'Paul';
document.getElementById('yourfile').value = 'c:\users\admin\desktop\myfile.jpg';
document.forms[0].submit();

I know the second line of the script above will throw an exception. Instead, I could click on the input:

document.getElementById('myfile').value = 'Paul';

But this will open a window to select the file, but I can't fill this window using JS... can I?

Is there any workaround for this? Or is the only way to select a file in a web form manually?

CodePudding user response:

...i can't fill this window using JS... or can i ?

No, you are not able to fill that form through JavaScript.

If you could, it would allow websites to take files from your computer without your knowledge, which would be a huge security violation. That's why it makes a window open on your desktop: so that the user knows that the site is trying to download a file.

[Are there] any [workarounds] for this or the only way to select a file in a web form is manually?

No, there are no workarounds for this feature.

As I said above, it would be a major security issue if you could do this, so the only way to get a file from a user is to use the popup window.

  • Related