javascript 通过 XHR 请求下载 PDF 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20260212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PDF file download through XHR Request
提问by Ch Faizan Mustansar
Is it totally impossible to download a pdf file through an XHR request?
I know there are many other discussions already on this topic but sadly, I am still not satisfied with them.
I am using AngularJs and making a request by using its $Http
method. It is not returning any file download popup. But if I hit with the same URL in a new Browser Window then I am getting a popup.
I have already tried a work-arround and its working fine i.e. document.location.href = url;
but If I do this then I am unable to show the waiting image till the time the download popup is ready and appeared.
So the work arround is not enough for me. I would like to do it with a genuine way through a request to the server through which I can handle the alternative flows of the outcome as well.
通过 XHR 请求下载 pdf 文件是完全不可能的吗?我知道关于这个话题已经有很多其他的讨论,但遗憾的是,我仍然对它们不满意。我正在使用 AngularJs 并使用它的$Http
方法发出请求。它不会返回任何文件下载弹出窗口。但是,如果我在新的浏览器窗口中使用相同的 URL,则会弹出一个窗口。我已经尝试了一个 work-arround 并且它工作正常,即document.location.href = url;
但是如果我这样做,那么在下载弹出窗口准备好并出现之前,我无法显示等待图像。所以周围的工作对我来说还不够。我想通过对服务器的请求以一种真正的方式来做到这一点,我也可以通过它来处理结果的替代流程。
回答by muneebShabbir
Have a look at this JQuery plugin jquery-file-download-pluginand here is the demo page of this plugin demo. I think its inserting iframe dynamically to DOM and produces look and feel just like AJAX request. It might be helpful for you.
看看这个 JQuery 插件 jquery-file-download-plugin,这里是这个插件演示的演示页面 。我认为它动态插入 iframe 到 DOM 并产生外观和感觉就像 AJAX 请求。它可能对你有帮助。
回答by Moritz Petersen
It certainly depends on the size of the PDF file, but this would be a workable approach if the PDF isn't too large:
这当然取决于 PDF 文件的大小,但如果 PDF 不是太大,这将是一种可行的方法:
Show the "waiting image" and download the PDF using
$http
.$http.get('http://my.example.com/foo.pdf').success(function(pdfData) { ... do something with pdfData ... });
Convert
pdfData
to Base64 encoding and use a data URI schemeto create a URL for the downloaded PDF file.- Redirect to that URL.
显示“等待图像”并使用 下载 PDF
$http
。$http.get('http://my.example.com/foo.pdf').success(function(pdfData) { ... do something with pdfData ... });
转换
pdfData
为 Base64 编码并使用数据 URI 方案为下载的 PDF 文件创建 URL。- 重定向到该 URL。