溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在Django中使用StreamingHttpResponse與FileResponse對文件進行下載

發(fā)布時間:2021-01-08 16:22:26 來源:億速云 閱讀:369 作者:Leah 欄目:開發(fā)技術

這篇文章將為大家詳細講解有關如何在Django中使用StreamingHttpResponse與FileResponse對文件進行下載,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

1 StreamingHttpResponse下載

StreamingHttpResponse(streaming_content):流式相應,內容的迭代器形式,以內容流的方式響應。

注:StreamingHttpResponse一般多現(xiàn)實在頁面上,不提供下載。

以下為示例代碼

def streamDownload(resquest):
 def file_iterator(filepath, chunk_size = 512):
 with open(filepath, 'rb') as f:
  while True:
  con = f.read(512)
  if con:
   yield con
  else:
   break
 filename = os.path.abspath(__file__) + 'test.txt'
 response = StreamingHttpResponse(file_iterator(filename)
 return response 
# 最后程序會將結果打印在顯示器上

2 FileResponse下載

FileResponse(stream):以流形式打開后的文件

注:FileResponse是StreamingHttpResponse的子類

以下為示例代碼:

def homeproc2(request):
 cwd = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 response = FileResponse(open(cwd + "/msgapp/templates/youfile", "rb"))
 response['Content-Type] = 'application/octet-stream'
 response['Content-Disposition'] = 'attachment;filename="filename"'
 return response

需要解釋說明的是:

 response['Content-Type] = 'application/octet-stream'
 response['COntent-Disposition'] = 'attachment;filename="filename"'
  • Content-Type:用于指定文件類型。

  • COntent-Disposition:用于指定下載文件的默認名稱,對,沒錯! “CO”兩個字符都要大寫。

關于如何在Django中使用StreamingHttpResponse與FileResponse對文件進行下載就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI