天天看點

django+ajax用FileResp

問題:

  公司的需求是從mongodb中查找資料并下載下傳回本地,但是在将檔案從mongodb通過django服務端,然後從django服務端向浏覽器下載下傳檔案。但是在下載下傳的時候出了些問題。由于是用的ajax請求,異步的,是以在将檔案傳回到前端的時候,前端的script标簽中的success回調函數中有資料,且是string類型。

解決辦法:

  在回調函數中設定重定向到檔案所在的url

——代碼——

django下載下傳檔案到浏覽器:

from django.http import FileResponse
def filedownload(request,filepath):
    file = open(filepath, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="example.tar.gz"'
    return response           

複制

前端script标簽中的ajax請求:

<script>

        $(".sub").on("click", function () {
            $.ajax({
                url: "/download",
                type: "post",
                data: {
                    id1: $("#id1").val(),
                    id2: $("#id2").val(),
                    start_date: $("#start_date").val(),
                    end_date: $("#end_date").val(),
                },
                success: function (data) {
                        var path = data.path;
                        location.href = path # 重定向到檔案所在的路徑
                }

            })

        });
    </script>           

複制

django+ajax用FileResp