JavaScript ajax下载文件

 

JavaScript Ajax http get 方法,利用a标签下载文件流。

文件流:django返回文件流 示例

from django.http import StreamingHttpResponse


class DownloadExportExcel(View):
    def get(self, request, *args, **kwargs):
        file_name = request.GET.get("filename")
        # print("DownloadExportExcel file_name: ", file_name)
        def file_iterator(file_name, chunk_size=512):
            with open(file_name, 'rb') as f:
                while True:
                    c = f.read(chunk_size)
                    if c:
                        yield c
                    else:
                        break

        tmp_file_path = getattr(settings, "SEARCH_ID_POUR_OUT_TMP_PATH", "/tmp")
        file_path = tmp_file_path + file_name
        # file_path = file_name
        response = StreamingHttpResponse(file_iterator(file_path))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename*=UTF-8\"{0}\"'.format(file_name)
        return response

ajax 前端请求示例

 

        function exportSearchResult(filter_company_name, thisElement) {
                let search_type_val = $('#select').val();
                let search_ids_val = trimNValue($('#ids').val());
                let filter_strs_val = trimValue($('#filter_textarea').val());
                let notice_val = trimValue($('#notice_textarea').val());
                let search_ak_start_time = trimValue($('#search_ak_start_time').val());
                let search_ak_end_time = trimValue($('#search_ak_end_time').val());
                let search_ak_size = trimValue($('#search_ak_size').val());
                let export_company_name = filter_company_name
                {# jquery获取调用本函数的元素 #}
                console.log(thisElement);
                if (filter_company_name != ""){
                    filter_strs_val = trimValue(filter_company_name)
                }

                let datas = {
                        'search_type': search_type_val,
                        'search_ids': search_ids_val,
                        'filter_strs': filter_strs_val,
                        'notice': notice_val,
                        'export_company_name': export_company_name,
                        csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                    }
                if (search_type_val == "AK_LOG") {
                    datas["search_ak_start_time"] = search_ak_start_time
                    datas["search_ak_end_time"] = search_ak_end_time
                    datas["search_ak_size"] = search_ak_size
                }
                // 倒出提示
                let queryTime = "倒出Excel....  "
                $("#ordinary_message span").html(queryTime);
                $("#ordinary_message").removeClass("hide");
                flushQuerySecond = true;
                interval = setInterval(printSeconds, 1000, "导出中");
                {# 发起查询中禁用按钮,避免没查完又重复发起 #}
                thisElement.setAttribute("disabled", "disabled");
                thisElement.textContent = "导出中..." ;
                $.ajax({
                    type: 'POST',
                    url: '/export_excel',
                    data: datas,
                    success: function (text) {
                        // 这里是请求成功后的回调函数
                        // 您可以在这里处理文件下载的操作
                        var link = document.createElement('a');
                        link.style.display = 'none';
                        link.href = '/download_searchresult/?filename=' + encodeURIComponent(text);
                        link.setAttribute('download', text);
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        console.log("下载完毕~")
                        flushQuerySecond = false;
                        let notice_text = $("#ordinary_message span").text().replaceAll("中.... 已", "") + " 倒出成功~,请看默认下载路径";
                        notice_text = notice_text.replaceAll("导出中", "")
                        notice_text = notice_text.replaceAll(".", "")
                        displayOrdinaryNewMessage(notice_text, 60000);
                        thisElement.removeAttribute("disabled");
                        thisElement.textContent = "导出Excel" ;
                    },
                    error: function (response) {
                        let err_message = JSON.stringify(response);
                        $('#result').html('<p>出错:' + err_message + '</p>');
                        flushQuerySecond = false;
                        let notice_text = $("#ordinary_message span").text().replaceAll("中.... 已", "") + " 倒出excel失败!!!";
                        displayOrdinaryNewMessage(notice_text, 60000);
                        thisElement.removeAttribute("disabled");
                        thisElement.textContent = "导出Excel" ;
                    }
                });
                {#let queryTime = "查询中....  "#}
                {#$("#ordinary_message span").html(queryTime);#}
                {#$("#ordinary_message").removeClass("hide");#}
                {#flushQuerySecond = true;#}
                {#interval = setInterval(printSeconds, 1000);#}
                {#displayOrdinaryNewMessage("查询中......", 120000)#}
            }

 

posted on 2023-11-25 23:26  zhangmingda  阅读(470)  评论(0编辑  收藏  举报

导航