gpt4 book ai didi

javascript - 如何使用 JavaScript 打开文件?

转载 作者:数据小太阳 更新时间:2023-10-29 04:33:04 26 4
gpt4 key购买 nike

我有一个 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 文件?

最佳答案

注意:我假设您正在使用 Ajax.Request 中的 Prototype 框架打电话。

response object并不意味着直接写入,但是它确实具有 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);
}
});

(注意添加的 .responseText)

编辑: 好吧,那是行不通的...尝试这样的事情:

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

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

关于javascript - 如何使用 JavaScript 打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/761682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com