简体   繁体   English

处理来自Ajax成功的PDF结果数据

[英]Handling PDF result data from ajax success

I wondered if anyone could suggest an alternative approach to the following work around. 我想知道是否有人可以提出一种替代方法来解决以下问题。

I have a web application that makes an http request for a PDF. 我有一个Web应用程序,可向PDF发出http请求。 The PDF can take more than the default timeout for a request to be created server side, so to better control this, I have used ajax, where as previously just window.open had been used. 对于要在服务器端创建的请求,PDF所花费的时间可能超过默认超时,因此,为了更好地控制它,我使用了ajax,而以前只使用window.open。

However, because of how the PDF is prepared, the request to create it, also returns it. 但是,由于PDF的准备方式,创建它的请求也会返回它。 I couldnt work out a way to handle the binary PDF data returned so I simply rellied on the browsers cache to store the data. 我想不出一种方法来处理返回的二进制PDF数据,所以我只是简单地放在浏览器缓存上存储数据。 Then simply requested against the same url again, but using window.open. 然后,只需使用window.open再次针对相同的URL请求即可。

The code for this is as follows.. 为此的代码如下。

function loadPdf(url, timeout){
   $.ajax({
     url: url,
     success: function(data){
       window.open(url);
     },
     error: function(error, status){
       window.alert("Problem retrieving PDF.\nThe error status is: " + status);
     },
     timeout: timeout,
     dataType: "application/pdf"   
  });
}

Really what I would like to do is handle the success data in a way that asks the user to open/save the PDF. 我真正想做的是以要求用户打开/保存PDF的方式处理成功数据。 I dont really like to use window.open in this way, especially as a repeat call like this. 我真的不喜欢以这种方式使用window.open,尤其是像这样的重复调用。

Really what I would like to do is handle the success data in a way that asks the user to open/save the PDF 我真正想做的是以要求用户打开/保存PDF的方式处理成功数据。

That's impossible. 这不可能。 You should not use AJAX to download files. 您不应该使用AJAX下载文件。 You can't do anything useful with the byte array that you retrieved in the success callback. 您不能对success回调中检索到的字节数组做任何有用的事情。 You can't directly save it on the client computer (for obvious reasons) and you can't prompt the user with the Save dialog neither. 您不能直接将其保存在客户端计算机上(出于明显的原因),也不能使用“保存”对话框来提示用户。

You don't need to use window.open either. 您不需要使用window.open You could simply provide a link to the file: 您只需提供指向该文件的链接:

<a href="/somescript">download pdf</a>

and then on the server specify the: Content-Disposition: attachment; filename="test.pdf" 然后在服务器上指定: Content-Disposition: attachment; filename="test.pdf" Content-Disposition: attachment; filename="test.pdf" custom HTTP header to show the save dialog allowing the user to specify a location on his computer to store the file. Content-Disposition: attachment; filename="test.pdf"自定义HTTP标头,以显示保存对话框,允许用户在计算机上指定存储文件的位置。

jquery.fileDownload插件会满足您的需求吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM