2017-10-03 3 views
1

업로드 된 파일 목록을 렌더링하는 Django보기가 있으며 사용자가이를 클릭하여 다운로드를 시작할 수 있습니다.HTML 파일 링크 - 강제 다운로드 항상

프로젝트를 배포 할 때 브라우저를 다운로드하는 대신 하나의 파일이 있음을 발견했습니다. 확장자 .dxf와 관련이있는 것 같습니다.

http://localhost:8003/media/folder/whatever.dxf 

그럼, 왜 같은 브라우저가 다르게 작동 : 결과

<a href="{{ MEDIA_URL }}{{ file.url }}" target="blank">...</a> 

:

이 링크를 만드는 방법입니까? localhost에서 실행하면 파일을 다운로드합니다. 그러나 실제 서버에 액세스하면 열 수 있습니다. 브라우저에서 서버가 서버를 열지 못하게 할 수 있습니까?

+1

. 브라우저는 일반적으로 PDF 및 txt 파일과 같이 브라우저에서 파일을 표시하도록 선택할 수 있습니다. 강제로 다운로드하도록 헤더를 설정하거나이를 위해 웹 서버를 구성해야합니다. – OptimusCrime

답변

0

다운로드를 처리 할 새로운 장고보기를 추가 할 수 있습니다.

urls.py

from django.conf.urls import url 
import views 

urlpatterns = [ 
    url(r'^download/$', views.DownloadView.as_view(), name='download') 
] 

views.py

import urllib 
from django.http import HttpResponse 
from django.views.generic.base import View 


class DownloadView(View): 
    def get(self, request): 
     location = request.GET.get('location') 
     file = urllib.urlretrieve(location) 
     contents = open(file[0], 'r') 
     content_type = '%s' % file[1].type 
     response = HttpResponse(contents, content_type=content_type) 
     response['Content-Disposition'] = 'attachment; filename="%s"' % location.split('/')[-1] 
     return response 

template.html 이것은 서버의 구성에 따라

<a href="/download/?location={{ MEDIA_URL }}{{ file.url }}">...</a>