在javascript中使用https路径下载pdf文件

时间:2018-05-30 08:58:18

标签: javascript jquery pdf download

我有一个对控制器的ajax调用,它在成功块中返回作为pd​​f文件的路径,看起来像这个www. bts.abcd.com/ReportPdf/BH00118051710501_1_1.pdf,现在我想在javascript中编写一些代码来下载这个文件。 我尝试了各种方法,如winodw.location.href="path",但这只在新窗口中打开文件而不下载它。 这是我的代码。

`

$.ajax({
      type: "POST",
     url: "/Reporting/ReportAPI",
     data: '{PatientId:"BH0012"}',
    contentType: "application/json,utf=charset-8",
    datatype: "JSON",
     success: function (response) {
//response= www.bts.abcd.com/ReportPdf/BH00118051710501_1_1.pdf
//Code for downloading the file
                }
            });

` 不同的方法也可以实现相同的结果。

2 个答案:

答案 0 :(得分:-1)

" winodw.location.href"无法在ajax块中工作。你可以创建一个元素,然后点击它。

答案 1 :(得分:-1)

已经提到过的一种方法是在JS中附加一个不可见的<iframe>并附加一个URL,但会出现一些安全错误。

<小时/> 在下面的方法中,我使用了Axios.js来安全下载包含Promises的文件。

  

Axios.JS CDN:<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>

JS

function DownloadFromUrl(url, mime) {
  axios({
    url: url,
    method: 'GET',
    responseType: 'blob', // important
  }).then((response) => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'file.' + mime);
    document.body.appendChild(link);
    link.click();
  });
}

$.ajax({
  type: "POST",
  url: "/Reporting/ReportAPI",
  data: '{PatientId:"BH0012"}',
  contentType: "application/json,utf=charset-8",
  datatype: "JSON",
  success: function(response) {
    // Response = URL
    // Mime     = File Type - pdf, jpeg, png, bmp, exe, js...
    DownloadFromUrl(response, "pdf");
  }
});

确保将MIME参数包装为字符串,或更改上面的代码以验证MIME Type

这是JSFiddle:https://jsfiddle.net/5mnethL1/2/

相关问题