Ajax下载包含大量数据的pdf文件

时间:2020-12-21 09:45:37

I am trying to download large pdf file from server and server takes some time to generate pdf and respond so request showing as pending.

我试图从服务器和服务器下载大型pdf文件需要一些时间来生成pdf并响应所以请求显示为挂起。

I need to show spinner when request starts and hide it when request is completed.

我需要在请求开始时显示微调器,并在请求完成时隐藏它。

How can I accomplish this using JavaScript ASP.NET MVC.

如何使用JavaScript ASP.NET MVC实现此目的。

---UPDATE------

Example controller looks like this:

示例控制器如下所示:

public ActionResult DownloadFile()
    {


        return File(@"C:\Temp2\HolidayInnReceipt.pdf", "application/pdf", "Report.pdf");

    }

---UPDATE------

Here is sample project.

这是示例项目。

3 个解决方案

#1


0  

You can implement this using the Ajax request..

您可以使用Ajax请求实现此功能。

Step 1 Create ajax call to create pdf file
Step 2 Return saved pdf file path and set the window.location to download the pdf

步骤1创建ajax调用以创建pdf文件步骤2返回保存的pdf文件路径并设置window.location以下载pdf

At Step 1 -- you can show the spinner using the below approach:
jQuery – AJAX Loading Effect: A Simple Way to Display Content Using AJAX Request

在第1步 - 您可以使用以下方法显示微调器:jQuery - AJAX加载效果:使用AJAX请求显示内容的简单方法

Example:

   <body onload="loadingAjax('myDiv');">
    <div id="myDiv">
        <img id="loading-image" src="ajax-loader.gif" style="display:none;"/>
    </div>
</body>

and the script -

和脚本 -

<script>
function loadingAjax(div_id) {
      var divIdHtml = $("#"+div_id).html();
      $.ajax({
           type: "POST",
           url: "controller/method", //URL which generate pdf
           data: "data here",
           beforeSend: function() {
              $("#loading-image").show();
           },
           success: function(msg) {
              $("#loading-image").hide();
              window.location= msg.FilePath;
           }
      });
}
</script> 

References:
Display Ajax loader before load data

参考:在加载数据之前显示Ajax加载程序

#2


0  

Add Below CSS

<style>
#overlay {
    position: fixed;
    display: none;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.5);
    z-index: 99;
    cursor: pointer;
}</style>

In Form Tag

 <button class="btn btn-default btn-lg" onclick="ConfirmDialog('Are you sure you want To Download?')">Download</button>
<br /><br />
<div id="overlay">
    <div id="text">
        <img src="~/assets/images/loadingimage.gif" style="width:5%;" /><span> &nbsp; Downloading....</span>
    </div>
</div>
<label class="error-msg" style="color:green;" itemid="lblmsg"></label>

Script Tag

<script type="text/javascript">
    function ConfirmDialog(message) {
        debugger;

        var x = window.confirm(message)
        debugger;
        if (x) {
            on();               
            $.ajax({
                url: '@Url.Action("YourMVC_Method", "Controller")',
                type: 'GET',
                contentType: 'application/json;charset=utf-8',
                success: function (result) {
                    debugger;
                    $("label[itemid='lblmsg']").show();
                    $('label[itemid="lblmsg"]').text('DownloadSuccess');
                    off();
                },
                error: function (ex) {
                    //alert(ex);
                    $('label[itemid="lblmsg"]').hide();
                    off();
                }
            });
        }
        else {
            $('label[itemid="lblmsg"]').hide();
            off();
        }
    }
    function on() {
        document.getElementById("overlay").style.display = "block";
    }

    function off() {
        document.getElementById("overlay").style.display = "none";
    }
</script>

#3


0  

You can use URL.createObjectURL to get temporary url for downloaded blob object then just use link with download attribute.

您可以使用URL.createObjectURL获取下载的blob对象的临时URL,然后只使用带有download属性的链接。

<div id="spinner" style="display: none;">Loading...</div>
<button onclick="downloadPDF()">Download</button>
function downloadPDF () {
  const spinner = document.getElementById("spinner")

  spinner.style.display = "block"

  fetch('YOUR_URL_HERE')
    .then(resp => resp.blob())
    .then(blob => {
      const href = URL.createObjectURL(blob)
      const link = document.createElement('a')

      link.href = href;
      link.download = "filename.pdf"
      link.click()

      spinner.style.display = "none"
    })
}

#1


0  

You can implement this using the Ajax request..

您可以使用Ajax请求实现此功能。

Step 1 Create ajax call to create pdf file
Step 2 Return saved pdf file path and set the window.location to download the pdf

步骤1创建ajax调用以创建pdf文件步骤2返回保存的pdf文件路径并设置window.location以下载pdf

At Step 1 -- you can show the spinner using the below approach:
jQuery – AJAX Loading Effect: A Simple Way to Display Content Using AJAX Request

在第1步 - 您可以使用以下方法显示微调器:jQuery - AJAX加载效果:使用AJAX请求显示内容的简单方法

Example:

   <body onload="loadingAjax('myDiv');">
    <div id="myDiv">
        <img id="loading-image" src="ajax-loader.gif" style="display:none;"/>
    </div>
</body>

and the script -

和脚本 -

<script>
function loadingAjax(div_id) {
      var divIdHtml = $("#"+div_id).html();
      $.ajax({
           type: "POST",
           url: "controller/method", //URL which generate pdf
           data: "data here",
           beforeSend: function() {
              $("#loading-image").show();
           },
           success: function(msg) {
              $("#loading-image").hide();
              window.location= msg.FilePath;
           }
      });
}
</script> 

References:
Display Ajax loader before load data

参考:在加载数据之前显示Ajax加载程序

#2


0  

Add Below CSS

<style>
#overlay {
    position: fixed;
    display: none;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.5);
    z-index: 99;
    cursor: pointer;
}</style>

In Form Tag

 <button class="btn btn-default btn-lg" onclick="ConfirmDialog('Are you sure you want To Download?')">Download</button>
<br /><br />
<div id="overlay">
    <div id="text">
        <img src="~/assets/images/loadingimage.gif" style="width:5%;" /><span> &nbsp; Downloading....</span>
    </div>
</div>
<label class="error-msg" style="color:green;" itemid="lblmsg"></label>

Script Tag

<script type="text/javascript">
    function ConfirmDialog(message) {
        debugger;

        var x = window.confirm(message)
        debugger;
        if (x) {
            on();               
            $.ajax({
                url: '@Url.Action("YourMVC_Method", "Controller")',
                type: 'GET',
                contentType: 'application/json;charset=utf-8',
                success: function (result) {
                    debugger;
                    $("label[itemid='lblmsg']").show();
                    $('label[itemid="lblmsg"]').text('DownloadSuccess');
                    off();
                },
                error: function (ex) {
                    //alert(ex);
                    $('label[itemid="lblmsg"]').hide();
                    off();
                }
            });
        }
        else {
            $('label[itemid="lblmsg"]').hide();
            off();
        }
    }
    function on() {
        document.getElementById("overlay").style.display = "block";
    }

    function off() {
        document.getElementById("overlay").style.display = "none";
    }
</script>

#3


0  

You can use URL.createObjectURL to get temporary url for downloaded blob object then just use link with download attribute.

您可以使用URL.createObjectURL获取下载的blob对象的临时URL,然后只使用带有download属性的链接。

<div id="spinner" style="display: none;">Loading...</div>
<button onclick="downloadPDF()">Download</button>
function downloadPDF () {
  const spinner = document.getElementById("spinner")

  spinner.style.display = "block"

  fetch('YOUR_URL_HERE')
    .then(resp => resp.blob())
    .then(blob => {
      const href = URL.createObjectURL(blob)
      const link = document.createElement('a')

      link.href = href;
      link.download = "filename.pdf"
      link.click()

      spinner.style.display = "none"
    })
}