你可以簡單地添加一個url模式在例如。 urls.py
:
from django.conf.urls import url
from . import views
urlpatterns = [
...,
url(r'^uploadedFiles/(?P<file_name>.+)/$', views.download, name='download')
]
並且在例如所述控制器的download
方法。 views.py
建議在here:
import os
from django.conf import settings
from django.http import HttpResponse
# path to the upload dir
UPLOAD_DIR = 'D:\uploadedFiles'
...
def download(request, file_name):
file_path = os.path.join(UPLOAD_DIR, file_name)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/octet-stream")
response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path)
return response
else:
raise Http404
我們是否需要指定內容類型?上傳的文件可以是任何類型 –
不,我們不這樣做,但推薦按照[在這裏]解釋(http://stackoverflow.com/questions/20392345/is-content-type-http-header-always -需要)。我已經更新了示例,因此無論文件類型如何,它總是強制用戶下載 –
我必須將url模式更改爲'url(r'^ uploadedFiles /(?P [\ w \ - 。*] +)/ $ ',下載,名稱='下載'),'它工作。謝謝! –