Django實現(xiàn)文件的下載功能

前言:

最近工作中需要使用django實現(xiàn)文件的下載功能。自己通過file.read方式實現(xiàn)后,在測試的過程中,發(fā)現(xiàn)當(dāng)文件過大時,非常吃內(nèi)存,為了優(yōu)化 在網(wǎng)上找了一篇非常不錯的文章解決了該問題!

  • django版本:1.8.2
  • python版本:2.7.10
參考文章的出處:http://www.itdecent.cn/p/2ce715671340
實現(xiàn)思路詳解:

1.使用了django的StreamingHttpResponse對象,以文件流的方式下載文件;
2.使用了迭代器(file_iterator()方法),將文件進(jìn)行分割,避免消耗過多內(nèi)存;
3.添加響應(yīng)頭:Content-Type 和 Content-Disposition,讓文件流寫入硬盤

代碼:
# coding:utf-8

import json
import os
import traceback
import time

from django.http import HttpResponse
from django.http import StreamingHttpResponse

from rest_framework import viewsets
from rest_framework.decorators import list_route


class ExportFile(viewsets.GenericViewSet):
    @staticmethod
    def file_iterator(download_file, chunk_size=1024):
        with open(download_file) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    @list_route(methods=["GET"])
    def download(self, request):
        """下載"""
        file_path = "需要下載的文件路徑"
        if not os.path.exists(file_path):
            raise IOError("file not found!")
        try:
            file_name = os.path.basename(file_path)
            file_name = "{file_name}_{timestamp}".format(file_name=file_name, timestamp=int(time.time()))
            response = StreamingHttpResponse(self.file_iterator(file_path))
            response["Content-Type"] = "application/octet-stream"
            response["Content-Disposition"] = "attachment;filename={}".format(file_name)
            return response

        except Exception as e:
            logger.error(e.message)
            logger.error(traceback.format_exc())
            return HttpResponse(json.dumps({"success": False, "error": u"下載文件失敗"}), status=500,
                                content_type="text/json")

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容