我正在使用django-sendfile将大文件作为附件发送到用户界面。这适用于sendfile.backends.simple
后端,但是当我使用sendfile.backends.nginx
时,它会在nginx日志上返回404错误。
我认为我的nginx配置有问题。
views.py
class FileDownloadView(View):
def get(self, request, id_file):
obj = FileCombined.objects.get(id_file=id_file)
return sendfile(request, obj.path, attachment=True)
urls.py
from django.conf.urls import url
from django.urls import path
urlpatterns += [
path(r'file/id/<str:id_file>/delete/', FileDeleteView.as_view(), name='files-delete'),
path(r'file/id/<str:id_file>/download/', FileDownloadView.as_view(), name='files-download'),
]
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
SENDFILE_BACKEND = "sendfile.backends.nginx"
SENDFILE_ROOT = os.path.join(BASE_DIR, 'media')
SENDFILE_URL = '/media'
/etc/nignx/sites-enabled/myapp
server { # simple reverse-proxy
listen 80;
server_name localhost;
sendfile on;
# serve static files
location /static {
proxy_pass http://127.0.0.1:8000/static;
}
location /media/ {
internal;
root /home/foo/project/django-combine/media;
}
location / {
proxy_pass http://127.0.0.1:8000;
}
}
nginx/access.log
127.0.0.1 - - [30/Dec/2017:08:20:01 +0530] "GET /file/id/5114a7721b6943fb31fc143a20adbec630bb5eb2516d7574b881454209338eed/download/ HTTP/1.1" 404 208 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36"
127.0.0.1 - - [30/Dec/2017:08:25:01 +0530] "GET /file/id/5114a7721b6943fb31fc143a20adbec630bb5eb2516d7574b881454209338eed/download/ HTTP/1.1" 404 208 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36"
实际上我要下载的文件存在于/home/foo/project/django-combine/media
目录中。
print(obj.path)
/home/foo/project/django-combine/media/google-oauth2|817468732648743/33601a74-de02-4b83-8587-1f8c3d8c96fb/output/combined.csv
答案 0 :(得分:1)
您需要更改
root /home/foo/project/django-combine/media/;
到
root /home/foo/project/django-combine/;
因为root中的/media
是root /home/foo/project/django-combine/media/media
的有效路径。
您甚至可以使用alias /home/foo/project/django-combine/media/;
代替root /home/foo/project/django-combine/media/
。那也行得通。至于别名,位置路径没有附加
此外,您需要确保没有像|
那样的特殊符号,这使得nginx难以找到文件