django+ajax用FileResp

发布时间:2019-03-08 20:31:53编辑:auto阅读(2574)

    问题:

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

     

关键字

上一篇: 计算机硬件基础

下一篇: Python3 urllib 与 Pyt