如何防止以普通(纯文本)形式上传文件

How to prevent files uploads in normal (text-only) forms

<!DOCTYPE html>
<html>
<body>
<form action="/submit_page.php" method="post" enctype="multipart/form-data">

    Enter your first name and last name below :<br>
      First name: 
           <input type="text" name="fname"><br>
      Last name:
           <input type="file" name="lname" ><br>

    <input type="submit" value="Submit" name="submit">

</form>
</body> 
</html>

以上表格仅适用于两个输入字段

- 名字
- 姓氏

现在(假设是黑客)我已经将姓氏文本输入字段修改为姓氏文件输入并添加了enctype="multipart/form-data" 在表单属性中,我点击提交。

无论文件有多大,它都会随文件一起发送数据,并且服务器仍在临时接收它,这意味着它也在消耗我的服务器性能和带宽以及客户端带宽,但表单仅设计用于文本输入

所以我的问题是如何防止此类黑客攻击?

您无法控制发送或不发送到您的服务器的内容。这有点自相矛盾。为了知道请求是否有效,服务器需要读取请求,因此有点强迫你接受所有请求。

真的,黑客甚至不需要修改表单。他们可以独立地向您的服务器发送请求,而无需访问您的网页。

您可能想了解 Cloudflare 等服务。

如果用户只需要上传最大 5 MB 的文件和几个文本字段,则将总 POST 内容限制在 6 MB 左右。

这是另一个描述如何在 PHP 中做到这一点的答案:
Change the maximum upload file size

这是 NodeJS 的答案:

这里解释了为什么这是限制文件上传的唯一方法:

Limiting the size of uploads

Unfortunately the HTTP specification gets in the way again here. The only piece of useful information available before the contents of the POST is the total size of the POST. This includes all uploaded files, all other fields in the form, any headers etc. As a result, the only thing that we can use to limit uploads is the POST size (duh!). You'll want to consider a limit carefully - it should be low enough to prevent denial of service attack, but high enough to let your users upload the kinds of files you want them to.

来源:Stripes(我非常喜欢的 Java 服务器端框架)