如何使用JavaScript来打开一个文件? [英] How to open a file using JavaScript?

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

问题描述

我有写一个PDF文件作为一个ByteArrayOutputStream到servlet的输出流的servlet。 如果我打开servlet的URL,浏览器打开该文件。 但是,如果在servlet的出现错误时,浏览器会打开并显示错误消息的空PDF。 通过ServletResponse的发送一个错误的浏览器中打开默认的错误页面。

I have a servlet that write a pdf file as a ByteArrayOutputStream to the servlet's output stream. If I open the servlet URL the browser opens the file. But if occur an error on the servlet, the browser opens an empty pdf with an error message. Sending an error through the ServletResponse the browser opens the default error page.

我想发送一个错误信息,而不重定向到一个错误页面或打开一个无效的PDF文件。

I want to send an error message without redirecting to an error page or opening an invalid pdf file.

我想:

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打开一个页面, [对象的对象]

But, onSuccess opens a page with [object object]

使用JavaScript我如何可以打开一个PDF文件?

How can I open a PDF file using JavaScript?

推荐答案

注:我在你使用的的 的Ajax.Request 调用。

Note: I'm assuming you're using the Prototype framework from the Ajax.Request call.

借助响应对象是注定不会被直接写入,但它确实,有的responseText 应包含返回PDF属性。

The response object isn't meant to be written directly, it does however, have the responseText property which should contain the returned PDF.

您是否尝试过:

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

编辑:好了,没有工作......尝试是这样的:

Okay, so that didn't work... Try something like this:

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

这是什么会做的是创建Ajax请求,如果成功打开它在一个新的窗口。打开新窗口要快而实际上不需要再次请求PDF因为浏览器应该具有的Ajax.Request通话过程中缓存的。

What this will do is create the ajax request, and if successful open it in a new window. Opening the new window should be fast and not actually require requesting the PDF again since the browser should have cached it during the Ajax.Request call.

这篇关于如何使用JavaScript来打开一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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