如何使用JavaScript打开文件?

Dan*_*ura 7 javascript pdf ajax prototypejs

我有一个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);
        }
    });
Run Code Online (Sandbox Code Playgroud)

但是,onSuccess打开一个包含[object object]的页面

如何使用JavaScript打开PDF文件?

Ben*_*n S 10

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

响应对象并不意味着要直接写入,但它的确有responseText它应该包含返回的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);
        }
    });
Run Code Online (Sandbox Code Playgroud)

(注意添加.responseText)

编辑:好的,所以这不起作用...尝试这样的事情:

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

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