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)
# 写入创建 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
网友评论