django+ajax将文件下载到浏览器过程中遇到的问题

python学习网 2018-09-12 14:10:02

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

 

前端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>

问题:

  需求是要从mongodb中查找数据并下载回本地,但是在将文件从mongodb拉回django服务端,从django服务端向浏览器下载的时候出了问题。由于是用的ajax请求,一开始是直接将return response。

 

但是由于是异步,所以response并不会在浏览器下载,而是到了ajax中的success中的data,且是string类型,我判断它是由于异步所以并不能直接下载,因此就将response单独拿出来封装成一个函数并写了一个url指向它,从mongodb拉回来文件之后,redirect到response函数的接口,然后用函数去返回文件下载。

阅读(1136) 评论(0)