为什么没有 enctype 属性无法上传文件? [英] Why does file upload not work without the enctype property?

查看:22
本文介绍了为什么没有 enctype 属性无法上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数时候,文件上传错误的根源是我们忘记在HTML表单中添加enctype属性.

Most of time, the source of file uploading errors are that we forget to add the enctype property in the HTML form.

通常,我们不需要为常规请求添加 enctype 属性.但是,我们确实需要在上传文件时将其添加到 HTML 表单中,

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"

我只是好奇,为什么没有 enctype 属性无法上传文件?

I'm just curious, why does uploading files not work without the enctype property?

推荐答案

multipart/form-data" enctype 由 RFC 1867 指定,您可以查看 此处 了解更多技术概述.

The "multipart/form-data" enctype is specified by RFC 1867 which you can review here for more of a technical overview.

在 HTML 表单中,数据表示为多个字段.当使用 multipart/form-data 作为 enc 类型时,浏览器将表单字段作为一系列部分"发送,每个部分都有一个内容类型标头来描述存储在该部分中的数据类型.对于普通表单字段,此内容类型通常设置为文本/纯文本".该内容类型仅在使用 multipart/form-data enctype 时由浏览器发送.

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.

对于file"类型的输入元素,内容类型是application/octet-stream"或类似的东西,它向服务器端软件表明该字段的内容不是典型的纯文本,而是一个文件,应该以不同的方式处理.

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.

文件"类型的输入元素在不使用multipart/form-data"时不起作用的原因是因为服务器无法识别该字段的内容与普通文本字段(因为除非使用 multipart/form-data,否则浏览器不会发送内容类型),因此它将字段内容作为普通文本处理.当使用正确的 enctype 并且服务器可以正确识别字段包含的数据类型时,服务器知道将字段的内容作为文件数据而不是文本来处理,并且可以正确处理它.

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.

这篇关于为什么没有 enctype 属性无法上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆