詳解Django關(guān)于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法
StreamingHttpResponse(streaming_content):流式相應(yīng),內(nèi)容的迭代器形式,以內(nèi)容流的方式響應(yīng)。
注: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 # 最后程序會將結(jié)果打印在顯示器上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é)議里面的標準類型。
到此這篇關(guān)于詳解Django關(guān)于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法的文章就介紹到這了,更多相關(guān)Django StreamingHttpResponse與FileResponse內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 在vue中獲取wangeditor的html和text的操作2. 使用vue-cli創(chuàng)建項目并webpack打包的操作方法3. Python用K-means聚類算法進行客戶分群的實現(xiàn)4. Python加載數(shù)據(jù)的5種不同方式(收藏)5. python mysql 字段與關(guān)鍵字沖突的解決方式6. python編寫五子棋游戲7. Java xml數(shù)據(jù)格式返回實現(xiàn)操作8. 解決Android Studio Design界面不顯示layout控件的問題9. python讀取中文路徑時出錯(2種解決方案)10. Java源碼解析之接口List
