使用 Ajax 下载并打开 PDF 文件 [英] Download and open PDF file using Ajax

查看:43
本文介绍了使用 Ajax 下载并打开 PDF 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成 PDF 的操作类.contentType 设置适当.

I have an action class that generates a PDF. The contentType is set appropriately.

public class MyAction extends ActionSupport 
{
   public String execute() {
    ...
    ...
    File report = signedPdfExporter.generateReport(xyzData, props);

    inputStream = new FileInputStream(report);
    contentDisposition = "attachment="" + report.getName() + """;
    contentType = "application/pdf";
    return SUCCESS;
   }
}

我通过 Ajax 调用调用此 action.我不知道如何将此流传送到浏览器.我尝试了一些东西,但没有任何效果.

I call this action through an Ajax call. I don't know the way to deliver this stream to browser. I tried a few things but nothing worked.

$.ajax({
    type: "POST",
    url: url,
    data: wireIdList,
    cache: false,
    success: function(response)
    {
        alert('got response');
        window.open(response);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) 
    {
        alert('Error occurred while opening fax template' 
              + getAjaxErrorString(textStatus, errorThrown));
    }
});

上面给出了错误:

您的浏览器发送了此服务器无法理解的请求.

Your browser sent a request that this server could not understand.

推荐答案

为此,您不一定需要 Ajax.如果您在服务器端代码中将 content-disposition 设置为 attachment,只需一个 链接就足够了.这样父页面将保持打开状态,如果这是您的主要关注点(否则为什么您会不必要地为此选择 Ajax?).此外,没有办法很好地异步处理这个问题.PDF 不是字符数据.是二进制数据.你不能做像 $(element).load() 这样的事情.您想为此使用全新的请求.对此,pdf 非常合适.

You don't necessarily need Ajax for this. Just an <a> link is enough if you set the content-disposition to attachment in the server side code. This way the parent page will just stay open, if that was your major concern (why would you unnecessarily have chosen Ajax for this otherwise?). Besides, there is no way to handle this nicely acynchronously. PDF is not character data. It's binary data. You can't do stuff like $(element).load(). You want to use completely new request for this. For that <a href="pdfservlet/filename.pdf">pdf</a> is perfectly suitable.

为了在服务器端代码方面为您提供更多帮助,您需要详细说明所使用的语言并发布代码尝试的摘录.

To assist you more with the server side code, you'll need to tell more about the language used and post an excerpt of the code attempts.

这篇关于使用 Ajax 下载并打开 PDF 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆