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 :)
- The input load file to memory when selecting uploading file or not?
- No it just save file path. I use process monitor then select file nearly 200Mb, both chrome and firefox not eat more memory, or reading disk; I can even delete this file before clicking submit button.
- How enctype of form effect to the input?
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?)
- What does server side do when receiving the data?
- As said above, I only care about PHP, and what PHP give us is:
// 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.
- How do CakePHP do with uploaded file?
- It's same as what PHP do just put it in $this->request and we must ensure that their names must be data[] or simply just use $this->Form->form("")
- Can I preview image or do something with selected file before submitting it to server?
- Yes. You can listen on
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?)