- Атрибут enctype
- Как правильно задавать?
- Какие значения могут быть записаны в атрибут?
- В каких тегах применяется?
- Пример использования
- HTML enctype Attribute
- Browser Support
- Syntax
- Attribute Values
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Understanding HTML Form Encoding: URL Encoded and Multipart Forms
- URL Encoded Form
- Multipart Forms
- Content-Type Header
- Request Body
- Text/plain Forms
Атрибут enctype
Служит для кодировки информации из формы для сервера, на котором обрабатываются данные. В обычной практике использованием атрибута можно пренебречь, так как сервер в состоянии распознавать типы данных сам. Исключением является использование поля-загрузчика документов. В таком случае для атрибута просто необходимо прописать значение multipart/form-data для корректной работы сервера с данными из формы.
Как правильно задавать?
form enctype="application/x-www-form-urlencoded">формаform>
Какие значения могут быть записаны в атрибут?
- application/x-www-form-urlencoded — этому значению соответствует замена пробелов обозначением «+» и интерпретация букв в шестнадцатеричную систему кодировки. Это значение используется по умолчанию.
- multipart/form-data — никакой кодировки не осуществляется, используется для передачи файлов.
- text/plain — меняются только пробелы на символ «+», остальное все остается без изменений.
В каких тегах применяется?
Пример использования
DOCTYPE html> html> head> meta charset="utf-8"> title>Атрибут enctypetitle> head> body> form> p>Имя: input name="user">p> p>Резюме: input name="file" type="file">p> p>button formaction="handler.php" formmethod="post" formenctype="multipart/form-data">Переслатьbutton> form> body> html>
HTML enctype Attribute
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
Note: The enctype attribute can be used only if method=»post» .
Browser Support
Syntax
Attribute Values
Value | Description |
---|---|
application/x-www-form-urlencoded | Default. All characters are encoded before sent (spaces are converted to «+» symbols, and special characters are converted to ASCII HEX values) |
multipart/form-data | This value is necessary if the user will upload a file through the form |
text/plain | Sends data without any encoding at all. Not recommended |
❮ HTML tag
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Understanding HTML Form Encoding: URL Encoded and Multipart Forms
Now, let us look at each form type with an example to understand them better.
URL Encoded Form
As the name suggests, the data that is submitted using this type of form is URL endcoded. Take the following form,
action="/urlencoded?firstname=sid&lastname=sloth" method="POST" enctype="application/x-www-form-urlencoded"> type="text" name="username" value="sidthesloth"/> type="text" name="password" value="slothsecret"/> type="submit" value="Submit" />
Here, you can see that the form is submitted to the server using a POST request, this means that it has a body. But how is the body formatted? It is URL encoded. Basically, a long string of (name, value) pairs are created. Each (name, value) pair is separated from one another by a & (ampersand) sign, and for each (name, value) pair, the name is separated from the value by an = (equals) sign, like say,
For the above form, it would be,
username=sidthesloth&password=slothsecret
Also, notice that we have some query parameters passed in the action URL, /urlencoded?firstname=sid&lastname=sloth .
Don’t the URL encoded body and the query parameters passed in the action URL look awfully similar? It’s because they are similar. They share the same format discussed above.
Try creating an HTML file with the above code and see how it’s submitted in the dev tools. Here is a snap,
The things to notice here are the Content-Type header which says application/x-www-form-urlencoded , the query string and the form fields are transferred to the server in the format as discussed above.
Note: Don’t get confused by the term Form Data in the screen shot. It’s just how Google Chrome represents form fields.
All is fine, but there is a little more to the encoding process. Let’s introduce some spaces in the submitted values, take the below form which is the same as the previous one but has the firstname value changed from sid to sid slayer and username value changed from sidthesloth to sid the sloth .
action="/urlencoded?firstname=sid slayer&lastname=sloth" method="POST" enctype="application/x-www-form-urlencoded"> type="text" name="username" value="sid the sloth"/> type="text" name="password" value="slothsecret"/> type="submit" value="Submit" />
Now try to submit the form and see how the form fields are transferred in the dev tools. Here is a dev tools snap in Chrome.
Clearly, you can see that the spaces are replaced by either ‘%20’ or ‘+’. This is done for both the query parameters and the form body.
Read this to understand when + and %20 can be used. This encompasses the URL encoding process.
Multipart Forms
Multipart forms are generally used in contexts where the user needs files to be uploaded to the server. However, we’ll just focus on simple text field based forms, as is it enough to understand how they work.
To convert the above form into a multipart form all you have to do is to change the enctype attribute of the form tag from application/x-www-form-urlencoded to multipart/form-data .
action="/multipart?firstname=sid slayer&lastname=sloth" method="POST" enctype="multipart/form-data"> type="text" name="username" value="sid the sloth"/> type="text" name="password" value="slothsecret"/> type="submit" value="Submit" />
Let’s go ahead and submit it and see how it appears in the dev tools.
There are the two things to notice here, the Content-Type header and the payload of the form request. Let’s go through them one by one.
Content-Type Header
The value of the Content-Type header is obviously multipart/form-data . But it also has another value, boundary . The value for this in the example above is generated by the browser, but the user can very well define it as well, say for example, boundary=sidtheslothboundary . We’ll get to see how it’s useful in the next section.
Request Body
The request payload contains the form fields themselves. Each (name, value) pair is converted into a MIME message part of the following format,
The above format is repeated for each (name, value) pair.
Finally, the entire payload is terminated by the boundary value suffixed with a — . So the entire request looks like,
Now, we see how the boundary value is used.
In the case of an application/x-www-form-urlencoded form, the & ampersand kind of acts as a delimiter between each (name, value) pair, enabling the server to understand when and where a parameter value starts and ends.
In the case of a multipart/form-data form, the boundary value serves this purpose. Say if the boundary value was XXX , the request payload would look like,
—XXX
Content-Disposition: form-data; name=»username»
sidthesloth
—XXX
Content-Disposition: form-data; name=»password»
The hyphens themselves are not part of the boundary value but rather needed as part of the request format. The Content-Type header for the above request would be,
Content-Type: multipart/form-data; boundary=XXX
This allows the browser to understand, when and where each field starts and ends.
Text/plain Forms
These forms are pretty much the same as the URL encoded forms, except that the form fields are not URL encoded when sent to the server. These are not used widely in general, but they have been introduced as a part of the HTML 5 specification.
Avoid using them as they meant for human understanding and not for machines.
Payloads using the text/plain format are intended to be human readable. They are not reliably interpretable by computer, as the format is ambiguous (for example, there is no way to distinguish a literal newline in a value from the newline at
the end of the value).
Hope, I was clear in explaining what I learnt..See you in the next one guys..Peace.. 🙂
Get to know more about me on my website..✨