html 下載文件代碼


 

首先在html中加個a標簽

<a class="menu" href="/cmdb/file_down" download="ljctest.txt">文件下載</a>

接着在項目cmdb的urls.py(注,分流的urls.py) 添加
url(r'^file_down/', views.file_down),

接着在cmdb中的views.py添加 file_down的類
from django.http import StreamingHttpResponse
def file_down (request): #文本下載
import os
filename = os.path.join('filedown',"test.txt" ) # 要下載的文件路徑
# do something
the_file_name = 'test.txt' # 顯示在彈出對話框中的默認的下載文件名
response = StreamingHttpResponse(readFile(filename))
response['Content-Type'] = 'application/octet-stream' #表明他是一個字節流
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name) #默認文件名 不過好像加不加都沒什么關系
return response


def readFile(filename, chunk_size=512):
with open(filename, 'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break

效果圖如下:




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM