2017-03-22 65 views
1

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

想通了,所以給我想我會發布的問題。必須使用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函數中。