讓Django提供可下載的文件我希望網站上的用戶能夠下載路徑模糊的文件,這樣他們就不能直接下載。例如,我希望URL是這樣的,“http://example.com/download/?f=somefile.txt在服務器上,我知道所有可下載的文件都位于一個文件夾“/home/user/files/”中。有什么方法可以讓Django為下載文件提供服務,而不是試圖找到一個URL和View來顯示它呢?
3 回答

湖上湖
TA貢獻2003條經驗 獲得超2個贊
對于“兩個世界中最好的”,您可以將S.Lott的解決方案與xsendfile模塊:Django生成文件(或文件本身)的路徑,但實際文件由Apache/Lightttpd處理。一旦設置了mod_xsendfile,與視圖的集成需要幾行代碼:
from?django.utils.encoding?import?smart_str response?=?HttpResponse(mimetype='application/force-download')?#?mimetype?is?replaced?by?content_type?for?django?1.7response['Content-Disposition']?=?'attachment;?filename=%s'?%?smart_str(file_name)response['X-Sendfile']?=?smart_str(path_to_file)#?It's?usually?a?good?idea?to?set?the?'Content-Length'?header?too.#?You?can?also?set?any?other?required?headers:?Cache-Control,?etc.return?response
當然,只有當您控制您的服務器,或者您的托管公司已經設置mod_xsendfile時,這才能工作。
編輯:
mimetype被Django 1.7的content_type替換
response?=?HttpResponse(content_type='application/force-download'

烙印99
TA貢獻1829條經驗 獲得超13個贊
serve
from django.views.static import serve filepath = '/some/path/to/local/file.txt'return serve(request, os.path.basename(filepath), os.path.dirname(filepath))
添加回答
舉報
0/150
提交
取消