詳解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:用于指定下載文件的默認(rèn)名稱,對,沒錯! “CO”兩個字符都要大寫。
兩者都是MIME協(xié)議里面的標(biāo)準(zhǔn)類型。
到此這篇關(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. IDEA EasyCode 一鍵幫你生成所需代碼2. Ajax引擎 ajax請求步驟詳細(xì)代碼3. Java構(gòu)建JDBC應(yīng)用程序的實例操作4. Spring應(yīng)用拋出NoUniqueBeanDefinitionException異常的解決方案5. ThinkPHP5 通過ajax插入圖片并實時顯示(完整代碼)6. javascript設(shè)計模式 ? 建造者模式原理與應(yīng)用實例分析7. 一篇文章帶你了解JavaScript-對象8. Python使用oslo.vmware管理ESXI虛擬機的示例參考9. IntelliJ IDEA設(shè)置條件斷點的方法步驟10. Express 框架中使用 EJS 模板引擎并結(jié)合 silly-datetime 庫進行日期格式化的實現(xiàn)方法
