詳解Django關(guān)于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法
StreamingHttpResponse(streaming_content):流式相應(yīng),內(nèi)容的迭代器形式,以內(nèi)容流的方式響應(yīng)。
注:StreamingHttpResponse一般多現(xiàn)實(shí)在頁(yè)面上,不提供下載。
以下為示例代碼
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
需要解釋說(shuō)明的是:
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. Struts2獲取參數(shù)的三種方法總結(jié)2. JSP中Servlet的Request與Response的用法與區(qū)別3. IntelliJ IDEA刪除類的方法步驟4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程6. vue cli4下環(huán)境變量和模式示例詳解7. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式8. Django視圖類型總結(jié)9. IntelliJ IDEA導(dǎo)入jar包的方法10. Xml簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
