javascript 使用ajax从字节数组下载PDF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33174880/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:11:46  来源:igfitidea点击:

Download PDF from Byte array using ajax

javascriptjqueryajax

提问by Atul Jain

I am trying below code but this is creating file but not showing content. I need your anyone help, What i am doing wrong.

我正在尝试下面的代码,但这是创建文件但不显示内容。我需要你的任何人的帮助,我做错了什么。

    $.ajax({
    type: "POST",
    async : false,
    url: "/searchModel/createPDF",
    data:"my_param",
    contentType: 'application/octet-stream',  
    beforeSend:function(){

    }, 
    success: function(html) {
        /* html value is [37,80,68,75 .........] */
        //var file = new Blob([html], {type: 'application/pdf'});
        //var fileURL = URL.createObjectURL(file);
        //window.open(fileURL);

        var blob=new Blob([html],{type: 'application/pdf'});
        var link=document.createElement('a');
        link.href=window.URL.createObjectURL(blob);
        link.download="SearchedResults.pdf";
        link.click();

    }
 }); 

Response coming from server is in byte array [37,80,68,75 .........]

来自服务器的响应在字节数组中 [37,80,68,75 .........]

Please help me if data in bytes array how it would be convert in pdf.

如果字节数组中的数据如何转换为 pdf,请帮助我。

回答by Kishore Sahasranaman

You cannot use AJAX to download files. It doesn't make sense. You can send the AJAX request and fetch the file contents inside the success handler on the client, but for obvious security reasons you can't do much with it. You cannot save it on the client computer and there's no javascript API allowing you to prompt the user where to save it.

您不能使用 AJAX 下载文件。这没有意义。您可以发送 AJAX 请求并在客户端的成功处理程序中获取文件内容,但出于明显的安全原因,您不能用它做太多事情。您无法将其保存在客户端计算机上,并且没有 javascript API 允许您提示用户将其保存到何处。

So to download files, don't use AJAX. Create an anchor pointing to your server side script that serves the file to be downloaded.

所以要下载文件,不要使用 AJAX。创建一个指向您的服务器端脚本的锚点,该脚本为要下载的文件提供服务。

Sample :

样本 :

window.downloadfile = function(e){
  window.location = "/searchModel/createPDF?" +  "my_param";
}
<a href="#" onclick="downloadfile()">download file</a>

回答by Atul Jain

Yes you people said correct does not mean while download PDF using AJAX.

是的,您说的正确并不意味着使用 AJAX 下载 PDF。

 window.location = "/searchModel/createPDF?" + "my_param";

is enough,Only we need to render pdf from server side. It is default downloadable.Thanks for your suggestions

就足够了,只需要我们从服务器端渲染pdf。默认可下载。感谢您的建议