I implemented an upload and download button. The upload button functions properly, but when I click the download button it tells me that the file I want to download does not exist - 'no file'. this is the code.
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 %}
Try to return the FileResponse object.
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)
Also, you can check whether file_path is built correctly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.