下载功能:文件不存在 - 'no file'



我实现了一个上传和下载按钮。上传按钮功能正常,但当我点击下载按钮时,它告诉我我想下载的文件不存在- 'no file'。这是代码

views.py:

def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path,'rb') as fh:
response = HttpResponse(fh.read(), content_type='application/pdf')
response['Content-Disposition'] = 'inline;filename='+os.path.basename(file_path)
return response
raise Http404

urls . py:

from django.urls import path
from . import views
from django.conf import settings
from django.views.static import serve
from django.urls import re_path
from django.conf.urls.static import static
app_name = 'projects'
urlpatterns = [
path('', views.projects, name='projects'),
path('new-project/', views.newProject, name='new-project'),
path('new-task/', views.newTask, name='new-task'),
re_path(r'^download/(?P<path>.*)$',serve, {'document_root':settings.MEDIA_ROOT}),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Html:

{% for project in projects %}
<li class="my-2">
{% if project.status == '1' %}
<span class="badge badge-danger" style="width: 50px;">Stuck</span>
{% elif project.status == '2' %}
<span class="badge badge-info" style="width: 50px;">Working</span>
{% else %}
<span class="badge badge-success" style="width: 50px;">Done!</span>
{% endif %}
<span class="title ml-1">{{ project }}</span>
<span class="value"> <span class="text-muted small">deadline: </span>{{ project.dead_line }}
<span class="text-muted small">({{ project.complete_per }}%)</span>
<span> <a href="{{project.pdf.url}} download="{{project.pdf.url}}""><button type="button" class="btn btn-primary" style="margin-left:47px;">Download Project</button></a> </span>
</span>
<div class="bars">
<div class="progress progress-xs">
<div class="progress-bar bg-success" role="progressbar" style="width: {{ project.complete_per }}%" aria-valuenow="{{ project.complete_per }}" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
</li>
{% endfor %}

尝试返回filerresponse对象

def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
try:
output_file = open(file_path, "rb")
except FileNotFoundError:
raise NotFound(
detail="Requested file doesn't exist.",
)
return FileResponse(output_file, as_attachment=True)

还可以检查file_path是否正确构建。

最新更新