tags:

views:

355

answers:

2

Most of time, the source of File Upload didn't work was forgetting enctype in HTML Form (for me).

Normally, we do not need to add enctype in HTML Form for regular requests. But we do need to add this in HTML Form for file upload...

enctype="multipart/form-data"

I just curious, why file upload didn't work without enctype.

Thanks.

+3  A: 

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.

James Black
+4  A: 

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.

Mark