Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

ajax - How to open a file using JavaScript?

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.

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

I tried:

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);
        }
    });

But, onSuccess opens a page with [object object]

How can I open a PDF file using JavaScript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Have you tried:

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);
        }
    });

(Notice the added .responseText)

Edit: 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);
        }
    });

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...