如何使瓶子拒绝上传过大的文件?

2024-03-29 09:39:24 发布

您现在位置:Python中文网/ 问答频道 /正文

Here是一种使用瓶子接受上传的方式:

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
</form>

from bottle import route, request

@route('/upload', method='POST')
def do_upload():
    myfile = request.files.get('file')
    size = len(myfile.read())  # oops the file is already read anyway!
    if size > 1024*1024:  # 1 MB
        return "File too big"

然而,使用这种技术,一个500 MB的文件无论如何都会被读取,然后才注意到它是一个“太大的文件”

问题:如何防止瓶子服务器甚至接受过大的上传文件,而不必先读取它(并浪费带宽/内存!)

如果不能仅使用瓶子,如何使用Apache+mod_wsgi(我目前使用这个)


Tags: 文件form瓶子readsizehererequest方式