Most of time, the source of file uploading errors are that we forget to add the enctype
property in the HTML form.
Normally, we do not need to add the enctype
property for regular requests. However, we do need to add this to the HTML form when uploading files,
enctype="multipart/form-data"
I'm just curious, why does uploading files not work without the enctype
property?
The "multipart/form-data" enctype is specified by RFC 1867 which you can review here for more of a technical overview.
In HTML forms, data is represented as several fields. When using multipart/form-data as the enc type, the browser sends the form fields as a series of "parts" which each have a content-type header to describe the type of data stored in the part. This content-type is usually set to "text/plain" for normal form fields. This content-type is only sent by the browser when the multipart/form-data enctype is used.
For input elements of type "file", the content type is "application/octet-stream" or something similar which indicates to the server side software that the contents of the field are not typical plaintext but are instead the contents of a file and should be handled differently.
The reason input elements of type "file" do not work whenever "multipart/form-data" is not used is due to the fact that the server has no way of identifying that the contents of the field are any different from a normal text field (since the browser does not send the content-type unless multipart/form-data is used) so it handles the contents of the field as normal text. When the proper enctype is used and the server can properly identify what type of data the field contains, the server knows to handle the contents of the field as file data instead of text and can process it properly.
You may want to look at the comments here: http://www.velocityreviews.com/forums/t137597-html-file-upload-using-enctype-multipart-form-data-in-form.html
Short answer is that the enctype tells the browser how to send the file. It won't be able to send the file without the correct encoding type.