I am not asking how to upload a file.
I am just wondering how, when you click on an html file element, it shows the local system folders.
Can we do that with any other html elements like buttons and inputs? If not, what is so special about files? How does it show system directories ?
NOTICE: I'm not gonna describe exactly how browser process with file input, but I will list step-by-step what I've done and its result to understand the input better; Though it may not help use to understand its inside mechanism, it will help you not be scared or confused when working with it. In my experiments, I'll use HTML, Apache + PHP with CakePHP, Firefox and Chrome to compare how it used in real world programming. Let's start :)
application/x-www-form-urlencoded
and text/plain
seem to IGNORE file input; only multipart/form-data
trigger the browser to read the file from the file path and send it. (to see more how enctype work refer here: What does enctype='multipart/form-data' mean?)// Upload 1 file Array ( [<input name in file input tag>] => Array ( [name] => <same as the name of selected to upload file> [type] => <type> [tmp_name] => <path of file in tmp folder will explain below> [error] => <0: error, maybe because of file size too large, 1: success> [size] => <size of file in bytes> ) ) // Upload multiple files (input name must be <someName>[]) Array ( [<input name in file input tag>] => Array ( [name] => [<array of name>] [type] => [<array of type>] [tmp_name] => [<array of tmp path>] [error] => [<array of error>] [size] => [<array of size>] ) )
Browser send request(contain file) to Apache; Apache forward the request to PHP; PHP extract the file from the request and save to file at tmp folder that we can see in [tmp_name]. In the end of PHP file, it remove the temp, so we must use move_uploaded_file
before script ended if needing to save the file.
onchange
event of the file input; Through it DOM, we can access FileList then from its we can access in File; With FileReader (support in almost current browsers) we can read it as data url...(May see detail here: how to preview a image before and after upload?)The only html element that can give you access to the filesystem is that input
(of type file), because browsers allow it to show an open dialog, only the browser can do that, there is no way in any script API to access system directories. For security reasons there is no other current way to access the filesystem in that way (through a dialog); saving data locally through HTML5, forcing a download save dialog, or a print dialog are again, browser controlled actions, but you can invoke them from a webpage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With