詳解Django關(guān)于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法
StreamingHttpResponse(streaming_content):流式相應(yīng),內(nèi)容的迭代器形式,以內(nèi)容流的方式響應(yīng)。
注:StreamingHttpResponse一般多現(xiàn)實(shí)在頁面上,不提供下載。
以下為示例代碼
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 # 最后程序會(huì)將結(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)名稱,對(duì),沒錯(cuò)! “CO”兩個(gè)字符都要大寫。
兩者都是MIME協(xié)議里面的標(biāo)準(zhǔn)類型。
到此這篇關(guān)于詳解Django關(guān)于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法的文章就介紹到這了,更多相關(guān)Django StreamingHttpResponse與FileResponse內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 一款功能強(qiáng)大的markdown編輯器tui.editor使用示例詳解2. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程3. 利用CSS制作3D動(dòng)畫4. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)5. jsp+servlet簡單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))6. Python+unittest+requests 接口自動(dòng)化測(cè)試框架搭建教程7. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法8. PHP利用COM對(duì)象訪問SQLServer、Access9. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼10. Springboot 全局日期格式化處理的實(shí)現(xiàn)
