Servlet代码:
response.reset();
response.setContentType("application/pdf");
response.setHeader("Cache-control", "private");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Content-Disposition","attachment;filename=\"test.pdf\"" );
response.setContentLength(baos.size());
ServletOutputStream os =response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
Javascript客户端代码:
var request = new XMLHttpRequest();
var url = "http://localhost:800/WebApplication2/JSONDecode";
var method = "POST";
var async = true;
request.open(method, url, async);
request.setRequestHeader("Content-Type", "application/x-www-form- urlencoded; charset=utf-8");
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
alert(request.response);
window.open(request.response,"_blank");
}}
request.send("json=" + json);
在警告框中返回:
%PDF-1.4
%����
1 0 obj
<</ColorSpace/DeviceRGB/Subtype/Image/Height 1960/Filter/FlateDecode /Type/XObject/Width 1040/Length 651582/BitsPerComponent 8>>stream
x���wY�������}�}o�xﵹ]Uݕ��$I �o \br ��
我希望浏览器将其识别为pdf。我看了一遍,但看不出我做错了什么。浏览器页面从服务器发出错误400消息。
答案 0 :(得分:0)
想出来,所以考虑到我以为我会发布的问题。不得不使用getParams从指向pdf流的链接加载它。似乎运作良好,但如果任何人得到了更好的答案。
var rpdf = request.response;
if(request.readyState == 4 && request.status == 200) {
var getParams=jQuery('#createPO').serialize();
getParams=jQuery.trim(getParams);
getParams='http://myserver.com/WebApp/Servlet?'+getParams;
document.location=getParams;}
将其放入onreadystatechange函数。