如何限制上传文件的大小。 我正在使用 django 1.1 和 apache。 如果大小大于 100MB,我可以使用 apache 来显示一些 html 错误页面吗?
谢谢。
您可以在最新浏览器中的 JavaScript 中使用文件 API 来执行此操作:http://www.w3.org/TR/FileAPI/
例如(使用 jQuery):
var TYPES = ['image/jpeg', 'image/jpg', 'image.png'];
var file = $('#my_file_input')[0].files[0];
var size = file.size || file.fileSize;
var type = file.type;
if (size > MAX_BYTES) {
alert('Error: file too large');
} else if (TYPES.indexOf(type) < 0) {
alert('Error: file not a JPG or PNG');
} else {
// proceed with file upload
}
无需 Java 或 Flash。当然,您仍然需要对服务器进行某种检查,以检查禁用 JavaScript 的用户或恶意用户。如果不做服务器端验证,就有安全漏洞。
apache 有一个最大文件大小的服务器设置..(也不要忘记最大帖子大小)。我不相信 apache 可以自己显示错误页面,您可能可以使用 python 来显示错误页面。 不幸的是,我对 python 一无所知,所以除此之外我无法真正帮助你。 我知道 php 可以轻松做到这一点,所以我确信有一个适用于 python 的方法。
如果您想在上传开始之前获取文件大小,则需要使用 Flash 或 Java 小程序。
编写自定义上传处理程序是最好的方法。我认为像下面这样的东西会起作用(未经测试)。它会尽早终止上传。
from django.conf import settings
from django.core.files.uploadhandler import FileUploadHandler, StopUpload
class MaxSizeUploadHandler(FileUploadHandler):
"""
This test upload handler terminates the connection for
files bigger than settings.MAX_UPLOAD_SIZE
"""
def __init__(self, request=None):
super(MaxSizeUploadHandler, self).__init__(request)
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
if content_length > settings.MAX_UPLOAD_SIZE:
raise StopUpload(connection_reset=True)