from django.http import StreamingHttpResponse
def downloads(request, file_id):
# 得到即將下載文件的路徑和名稱
path, file_name = word_ok(file_id)
print(path) # 即將下載文件的路徑
print(file_name) #即將下載文件的名稱
response = StreamingHttpResponse(readFile(path))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="download.docx"'
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
# 生成文件,并返回文件的路徑和名稱
def word_ok(file_id):
file = models.file_information.objects.get(pk = file_id)
print("word名稱:", file.file_name)
# 寫入創(chuàng)建 word文件
document = docx.Document()
yiwen = models.yiwen.objects.filter(file = file)
for y in yiwen:
print(y.yiwen)
print(y.yiwen_style)
if len(y.yiwen_style) > 0:
document.add_paragraph(y.yiwen, style=y.yiwen_style)
else:
document.add_paragraph(y.yiwen)
path = "E:\\Man-Machine Translation System\\second_Edition\\static\\work\\yiwen_doc\\" + file.file_name
document.save(path)
# 返回文件的路徑和名稱
return path, file.file_name
python|Django 實現(xiàn)文件的下載
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。