How to set a value to a file input in HTML?
File inputs are locked boxes for security reasons—you cannot set a value to an <input type="file">
directly. However, you can trigger the file input dialog like so:
And grab the user-selected file using:
This approach preserves user control and autonomy over their files in an unobtrusive manner.
Security restraints—and how to work around them
Setting file input values programmatically with a client side disk system path is blocked by browsers. This is akin to a website reaching into your hard disk and grabbing files—clearly a privacy violation. However, these restrictions won't hinder our progress—we can still deal meaningfully with files while respecting boundaries!
Play nice with blobs and DataTransfer
If you have a Blob
or File
object from a server response or drag-and-drop operation, you can create a File
object—like a mini file in the browser's sandbox—and add that to your file input. Here's how,
Now, take your freshly minted File
object and simulate a drop event using the DataTransfer
object:
Easy peasy lemon squeezy, right? You're basically harnessing the power of a very obedient postman who only delivers letters (files) you say are okay.
Plan B
No luck with the File
and DataTransfer
method? Here are a few other techniques to enhance user experience and bypass the restriction (legally, of course):
- Image previews: Show users a sneak peek of their chosen image file.
- File download links: Let users download files which they then can upload manually.
- Clear/replace option: A checkbox or button to let users replace a previously selected file. Out with the old, in with the new!
Implementing the 'Impossible'—code snippets and caveats
Having crossed the security hurdle, time to get down to coding! Here's one way to fetch a file and manipulate your file input value using good 'ol JavaScript:
This script fetches a file and assigns this file to our file input by simulating user interaction.
UTF-8 character oopsies
It's not always sunshine and rainbows with File
objects, especially with UTF-8 characters. To handle those curveballs, make a slight adjustment:
Here, a handy TextEncoder
steps in to ensure our precious UTF-8 characters don't run into encoding issues. Phew!
Was this article helpful?