django+ajax用FileResponse文件下載到瀏覽器過程中遇到的問題


問題:

  公司的需求是從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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM