AJAX POST 到服务器导致错误 413:请求实体太大

AJAX POST to server results in Error 413: Request Entity Too Large

在 JS 插件中,我的 Django 视图接受 base64 编码图像的 AJAX POST。问题是图片太大了。我收到以下错误。

django_1    | Traceback (most recent call last):
django_1    |   File "/usr/local/lib/python3.6/site-packages/raven/transport/threaded.py", line 165, in send_sync
django_1    |     super(ThreadedHTTPTransport, self).send(url, data, headers)
django_1    |   File "/usr/local/lib/python3.6/site-packages/raven/transport/http.py", line 43, in send
django_1    |     ca_certs=self.ca_certs,
django_1    |   File "/usr/local/lib/python3.6/site-packages/raven/utils/http.py", line 66, in urlopen
django_1    |     return opener.open(url, data, timeout)
django_1    |   File "/usr/local/lib/python3.6/urllib/request.py", line 532, in open
django_1    |     response = meth(req, response)
django_1    |   File "/usr/local/lib/python3.6/urllib/request.py", line 642, in http_response
django_1    |     'http', request, response, code, msg, hdrs)
django_1    |   File "/usr/local/lib/python3.6/urllib/request.py", line 570, in error
django_1    |     return self._call_chain(*args)
django_1    |   File "/usr/local/lib/python3.6/urllib/request.py", line 504, in _call_chain
django_1    |     result = func(*args)
django_1    |   File "/usr/local/lib/python3.6/urllib/request.py", line 650, in http_error_default
django_1    |     raise HTTPError(req.full_url, code, msg, hdrs, fp)
django_1    | urllib.error.HTTPError: HTTP Error 413: Request Entity Too Large

关于如何解决这个问题有什么想法吗?我找到了 nginx 的解决方案,但是我在 cookiecutter-django 项目中使用 gunicorn

免责声明我强烈建议配置 Nginx 服务器以代理传递给 Gunicorn...

似乎 nginxclient_max_body_size 参数可能设置为低两级,以便处理后的图像能够毫无问题地发布到服务器。我讨厌服务器配置,但您需要编辑 nginx 配置。感觉可以通过在 nginx 配置中的 http{..} 块中添加以下行来轻松解决:

http {
    #...
    client_max_body_size 100m;
    client_body_timeout 1000s;
    #...
} 

这甚至可能在您站点的 nginx 配置文件的服务器块中 - yoursite_nginx.conf

server {
    # the port your site will be served on
    listen      8000;
    # the domain name it will serve for
    server_name example.com; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 100M;   # adjust to taste

    # max timeout duration
    client_body_timeout 1000s;  # adjust to taste

    # Django media
    location /media  {
        alias /path/to/your/mysite/media;  # your Django project's media files - amend as required
    }

    location /static {
        alias /path/to/your/mysite/static; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed
    }
}

请注意,您还需要 运行 服务器上的以下内容才能使更改生效:

$ service nginx reload

免责声明:请寻求服务器专家的专业建议! :)

想通了。 Django 的默认值对于 100mb 以上的图像来说太低了。

不得不更改

的设置
DATA_UPLOAD_MAX_MEMORY_SIZE = XXXX
FILE_UPLOAD_MAX_MEMORY_SIZE = XXXX