【问题标题】:How to open a file using JavaScript?如何使用 JavaScript 打开文件?
【发布时间】:2009-04-17 18:39:31
【问题描述】:

我有一个 servlet,它将 pdf 文件作为 ByteArrayOutputStream 写入 servlet 的输出流。 如果我打开 servlet URL,浏览器会打开文件。 但是,如果 servlet 发生错误,浏览器会打开一个带有错误消息的空 pdf。 通过 ServletResponse 发送错误浏览器会打开默认错误页面。

我想在不重定向到错误页面或打开无效 pdf 文件的情况下发送错误消息。

我试过了:

new Ajax.Request('/pdfservlet', {            
        onSuccess: function(response) {
            docWindow = window.open('','title');
            docWindow.document.open('application/pdf');
            docWindow.document.write(response);
            docWindow.document.close();
        },
        onFailure: function(response) {
            alert(response);
        }
    });

但是,onSuccess 打开一个页面 [对象对象]

如何使用 JavaScript 打开 PDF 文件?

【问题讨论】:

    标签: javascript ajax pdf prototypejs


    【解决方案1】:

    注意:我假设您正在使用来自 Ajax.Request 调用的 Prototype 框架。

    response object 并不是要直接编写的,但它确实具有应包含返回的 PDF 的 responseText 属性。

    你试过了吗:

    new Ajax.Request('/pdfservlet', {            
            onSuccess: function(response) {
                docWindow = window.open('','title');
                docWindow.document.open('application/pdf');
                document.write(response.responseText);
                docWindow.document.close();
            },
            onFailure: function(response) {
                alert(response);
            }
        });
    

    (注意添加的.responseText

    编辑:好的,那没用...试试这样的:

    new Ajax.Request('/pdfservlet', {            
            onSuccess: function(response) {
                window.open('/pdfservlet');
            },
            onFailure: function(response) {
                alert(response);
            }
        });
    

    这将创建 ajax 请求,如果成功,则在新窗口中打开它。打开新窗口应该很快,实际上不需要再次请求 PDF,因为浏览器应该在 Ajax.Request 调用期间缓存了它。

    【讨论】:

    • 这不会打开 pdf 应用程序。打开带有 %PDF-1.6 %���� 1 0 obj 的页面
    • 我添加了一个新的解决方案,它类似于 rde6173 建议的,但依赖于浏览器缓存。
    • 浏览器没有缓存。 pdf 需要两次。
    • 是的,在docs.sun.com/source/816-6408-10/document.htm#1196317 中列出的范围之外的 document.open mimetype 参数通常不起作用。在 Safari 和 Chrome 中,除了 text/html 之外没有其他 mimetype 可以工作。
    • @bobince,谢谢!很高兴知道。
    【解决方案2】:

    您可以尝试“两遍”方法。您使用 Ajax 调用 servlet(如果它动态生成 PDF,则让它缓存它)。如果成功,将用户重定向到带有参数的 servlet 以加载缓存的 PDF。

    还有其他选项,但这取决于您使用 PDF 的方式。

    我的 0.02 美元..

    【讨论】:

      【解决方案3】:

      由于您将 PDF 发送为“内联”而不是“附件”,因此您可以将 PDF 的 URL 放入动态创建的 Iframe 中,然后将该 Iframe 附加到叠加层。那会起作用的。

      -JP

      【讨论】:

        【解决方案4】:

        但是如果 servlet 发生错误,浏览器会打开一个带有错误消息的空 pdf。

        在我看来,尝试在服务器端解决这个问题比所有这些脆弱的 AJAX 和缓存摆弄更好。为什么 servlet 错误仍然在设置“Content-Type: application/pdf”标头及其错误消息?检查servlet中发送东西的顺序;在您成功创建 PDF 并准备好返回之前,不要发送“Content-Type”。

        【讨论】:

        • 我可以设置 'Content-Type: text/xml' 但是如何在客户端处理这个?
        • 简单地将其设置为 text/html 并提供一个漂亮的错误页面怎么样?然后您可以链接到该文件并让浏览器下载它或处理错误。如果这种错误可能在第二次尝试时消失,那么包含“重试”重新加载链接可能是合适的。
        • 这可行,但我不想打开错误页面。我想在同一页面中显示错误。
        猜你喜欢
        • 2013-06-10
        • 1970-01-01
        • 2017-12-02
        • 2011-04-04
        • 2012-09-23
        相关资源
        最近更新 更多