詳解Django關于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法
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”兩個字符都要大寫。
兩者都是MIME協(xié)議里面的標準類型。
到此這篇關于詳解Django關于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法的文章就介紹到這了,更多相關Django StreamingHttpResponse與FileResponse內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python使用PyMuPDF實現(xiàn)添加PDF水印
在日常工作中,我們經(jīng)常需要對PDF文件進行處理,其中一項常見的需求是向PDF文件添加水印,本文將介紹如何使用Python編程語言和PyMuPDF庫在PDF文件中添加水印,感興趣的可以了解一下2023-08-08Python-GUI?wxPython之自動化數(shù)據(jù)生成器的項目實戰(zhàn)
本文主要介紹了Python-GUI?wxPython之自動化數(shù)據(jù)生成器實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05Pytorch之ToPILImage()不輸出圖片問題及解決
這篇文章主要介紹了Pytorch之ToPILImage()不輸出圖片問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02