django中下載zip壓縮文件


項目需求:需要在列表頁面提供下載按鈕,下載補丁doc文檔,xls表格,版本序列,xxxx.pkg等文件的zip壓縮包。

參考鏈接:https://www.jb51.net/article/135951.htm

django中的views.py中的方法直接調用下面的例子即可。

具體實現:

import os
from django.http import StreamingHttpResponse

def file_down(request, file_path, file_name):
  
# 判斷下載文件是否存在 if not os.path.isfile(file_path): return HttpResponse("Sorry but Not Found the File") def file_iterator(file_path, chunk_size=512): """ 文件生成器,防止文件過大,導致內存溢出 :param file_path: 文件絕對路徑 :param chunk_size: 塊大小 :return: 生成器 """ with open(file_path, mode='rb') as f: while True: c = f.read(chunk_size) if c: yield c else: break try: # 設置響應頭 # StreamingHttpResponse將文件內容進行流式傳輸,數據量大可以用這個方法(.pdf,.mp3,.mp4等等什么樣格式的文件都可以下載) response = StreamingHttpResponse(file_iterator(file_path)) # 以流的形式下載文件,這樣可以實現任意格式的文件下載 response['Content-Type'] = 'application/octet-stream' # Content-Disposition就是當用戶想把請求所得的內容存為一個文件的時候提供一個默認的文件名 response['Content-Disposition'] = 'attachment;filename={file_name}{format}'.format( file_name=file_name, format=".zip") except: return HttpResponse("Sorry but Not Found the File") # 在這里千萬記得return,否則不會出現下載 return response

 


免責聲明!

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



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