我正在使用django-sendfile将大文件作为附件发送到UI。这适用于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
你需要改变
root /home/foo/project/django-combine/media/;
至
root /home/foo/project/django-combine/;
因为根中的/media
是root /home/foo/project/django-combine/media/media
的有效途径。
你甚至可以使用alias /home/foo/project/django-combine/media/;
而不是root /home/foo/project/django-combine/media/
。那也行得通。对于别名,不会附加位置路径
此外,你需要确保你没有像|
这样的特殊符号,这使得nginx很难找到文件