为什么在没有enctype属性的情况下文件上传不起作用? [英] Why does file upload not work without the enctype property?

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

问题描述

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



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

  enctype =multipart / form-data

我只是好奇,为什么没有 enctype 属性?

解决方案

multipart / form-dataenctype由RFC 1867指定,请阅读此处获取更多技术概述。

在HTML表单中,数据被表示为几个字段。当使用multipart / form-data作为enc类型时,浏览器将表单字段作为一系列部分发送,每个部分都有一个内容类型标题来描述存储在该部分中的数据类型。这种内容类型通常设置为普通表单域的text / plain。此内容类型仅在使用multipart / form-data enctype时由浏览器发送。



对于类型为file的输入元素,内容类型为应用程序/八位字节流或类似的东西,它向服务器端软件表明该字段的内容不是典型的明文,而是文件的内容,应该以不同的方式处理。



只要multipart / form-data未被使用,输入file类型元素的原因不起作用是因为服务器无法识别该字段的内容是否有任何不同从普通文本字段(因为除非使用multipart / form-data,浏览器不发送内容类型),所以它将字段的内容作为普通文本处理。当使用合适的enctype并且服务器可以正确识别字段包含的数据类型时,服务器知道将字段的内容作为文件数据而不是文本处理,并且可以正确处理它。


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.

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

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