此问题已在此处有答案:
How to send file to response in Django?(3个答案)
2天前关闭。
我想通过点击一个按钮下载一个包含所有附件的笔记到Django的zip文件中。
这就是观点:
def download_note(request, pk):
note = get_object_or_404(Note, pk=pk)
file_path = f'notes/media/downloaded_notes/note{note.id}.txt'
notefiles = NoteFile.objects.filter(note=note)
urls = [f.file.url for f in notefiles]
if get_language() == 'en':
content = f'Title: {note.title}, Author: {note.user}, Date: {note.add_date.strftime("%d-%m-%Y %H:%M:%S")}\n' \
f'Category: {note.category}\n' \
f'Note:\n{note.note_text}'
else:
content = f'Tytuł: {note.title}, Autor: {note.user}, Data: {note.add_date.strftime("%d-%m-%Y %H:%M:%S")}\n' \
f'Kategoria: {note.category}\n' \
f'Notatka:\n{note.note_text}'
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
zip_file_path = f'notes/media/downloaded_notes/note{note.id}.zip'
with zipfile.ZipFile(zip_file_path, 'w') as zipf:
zipf.write(file_path, os.path.basename(file_path))
media_root = settings.MEDIA_ROOT.replace('\\', '/')
print(media_root)
for url in urls:
print(f'{media_root}{url[6:]}')
#file_url = os.path.join(media_root, url[6:])
#zipf.write(file_url, os.path.basename(url[6:]))
file_name = os.path.basename(url)
zipf.write(f'{media_root}{url[6:]}', file_name)
with open(zip_file_path, 'rb') as f:
response = FileResponse(f.read(), content_type='application/zip')
response['Content-Disposition'] = f'attachment; filename="note{note.id}.zip"'
return response
当我点击下载按钮Chrome挂起几秒钟,然后文件下载。但是下载目录中的zip文件不起作用。当我试图打开它有一个消息说,该文件的格式无效或文件已损坏。但是当我进入django project和media/downloaded_notes/note70.zip时,一切都很好。
所以我认为这个片段有一个问题:
with open(zip_file_path, 'rb') as f:
response = FileResponse(f.read(), content_type='application/zip')
response['Content-Disposition'] = f'attachment; filename="note{note.id}.zip"'
这段代码有什么问题?
1条答案
按热度按时间x0fgdtte1#
请使用
HttpResponse
代替FileResponse