詳解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
需要解釋說明的是:
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. 推薦一個(gè)好看Table表格的css樣式代碼詳解2. 基于Surprise協(xié)同過濾實(shí)現(xiàn)短視頻推薦方法示例3. 不使用XMLHttpRequest對(duì)象實(shí)現(xiàn)Ajax效果的方法小結(jié)4. vue-electron中修改表格內(nèi)容并修改樣式5. 微信小程序?qū)崿F(xiàn)商品分類頁(yè)過程結(jié)束6. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式7. ASP新手必備的基礎(chǔ)知識(shí)8. AJAX實(shí)現(xiàn)文件上傳功能報(bào)錯(cuò)Current request is not a multipart request詳解9. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總10. ASP常用日期格式化函數(shù) FormatDate()
