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

查看:135
本文介绍了使用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调用。我不知道将此流传递给浏览器的方法。我尝试了一些但没有任何效果。

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。如果您将内容处置设置为附件,只需< a> 链接即可在服务器端代码中。通过这种方式,父页面将保持打开状态,如果这是您的主要关注点(为什么您会不必要地为此选择Ajax?)。此外,没有办法很好地同步处理这个问题。 PDF不是字符数据。这是二进制数据。你不能做像 $(element).load()这样的东西。您想要使用全新请求。为此< a href =pdfservlet / filename.pdf> pdf< / a> 非常合适。

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天全站免登陆