下载文件

url

 url(r'^api/down_dailyfiles/(\w)',views.down_dailyfiles),#下载

views.py

复制代码
@csrf_exempt
def down_dailyfiles(request,id):
    # 服务器上存放文件的路径
    try:
        monitor_result_id = int(id)
        # monitor_result_id = getint(request.GET.get("result_id"))
        monitor_result = Monitor_result.objects.filter(id=monitor_result_id).first()
        if not monitor_result_id:
            return JsonResponse({"status":1})

        file_path = monitor_result.file_path if monitor_result else ''
        filename = monitor_result.name if monitor_result else ''
        # filename = "1.txt"
        # dir = "D:/batch_config/template/"
        # file_path = os.path.join(dir, filename)
        if  monitor_result_id and not os.path.exists(file_path):
            logging.error("file_path:%s 不存在" % file_path)
            raise Http404("Download error")
        r = StreamingHttpResponse(open(file_path, "rb"))
        r["content_type"] = "application/octet-stream"
        r["Content-Disposition"] = "attachment;filename*=utf-8''{}".format(escape_uri_path(filename))

        return r
    except Exception:
        logging.error(traceback.format_exc())
        raise Http404("Download error")
复制代码

js

复制代码
function down_dailyfiles(id) {
            let url = "/api/down_dailyfiles/"+id
            $.ajax({
                url: url,
                data: {
                    result_id: id,
                },
                method: "GET",

                success: function (esponse, status, request) {
                    var disp = request.getResponseHeader('Content-Disposition');
                    if (disp && disp.search('attachment') != -1) { //判断是否为文件
                        var form = $('<form action="' +  url + '" method="post"></form>');
                        $('body').append(form);
                        form.submit(); //自动提交
                    }

                },
                error: function (e) {
                    toastr["error"](e, "错误")
                },

            })

        }
复制代码

 

posted on   小胖子方法  阅读(79)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示