2014-09-10 72 views
2

我試圖在使用Javascript的新窗口中彈出PDF文件的字節流。在新的瀏覽器窗口中顯示響應中的PDF字節流

在後端我使用Spring的控制器代碼如下

@RequestMapping(value = "/print", method = RequestMethod.POST, consumes="application/json") 
public ModelAndView printCompareChart(@RequestBody ChartGenerationRequest request, 
     HttpServletRequest httpRequest) throws Exception { 

    byte [] bytes =//bytestream of a pdf file 
    ModelAndView mav = new ModelAndView(); 
    mav.addObject("byteArray", bytes); 
    mav.setViewName("pdfByteArrayPrint"); 
    return mav; 
} 

給出這篇文章的方法是通過從JS AJAX調用這樣

$.ajax({ 
    url: url, 
    cache: false, 
    type:'POST', 
    data: JSON.stringify(data), 
    contentType:"application/json; charset=UTF-8", 
    success: function (responseData){ 
     var win=window.open('about:blank', target, windowProperties); 
     with(win.document) 
     { 
      open(); 
      write(responseData); 
      close(); 
     } 
    } 
}); 

從Chrome開發者工具稱爲我可以看到響應數據以字節形式出現,但在新的瀏覽器窗口中,它不顯示實際的pdf文件,而是顯示字節本身。

這是輸出我得到

output window 我怎麼能在這裏展示實際的文件,從字節流中提取?

+0

我送的JSON數據並取回PDF作爲流 – 2014-09-10 10:20:20

+0

'win.document'是一個HTML文檔。不要緊,你寫什麼。 – zeroflagL 2014-09-10 20:23:32

回答

0

我根本無法得到這個工作。所以我想出了一個替代方案。從JS端創建一個隱藏表單並提交數據,後端用pdf字節流回應,然後顯示在新的瀏覽器窗口中。在這種情況下,我不得不犧牲自動json轉換爲java對象,並單獨處理傳遞的httpRequest中的每個參數。

JS代碼

openWithPost = function(url, title, data, target) { 

    var form = document.createElement("form"); 
    form.action = url; 
    form.method = "POST"; 
    form.target = target || "_self"; 
    if (data) { 
    for (var key in data) { 
     var input = document.createElement('input'); 
     input.type = 'hidden'; 
     input.name = key; 
     input.value = data[key]; 
     form.appendChild(input); 
    } 
    } 
    form.style.display = 'none'; 
    document.body.appendChild(form); 
    form.submit(); 
} 

後端代碼春季

@RequestMapping(value = "/printCompareChart", method = RequestMethod.POST) 
public ModelAndView printCompareChart(HttpServletRequest httpRequest) 
{ 
    //get each parameter from httpRequest and handle it 
    String fileName = httpRequest.getParameter("fileName"); 
    //logic to create the pdf file 
    byte[] bytes = //get bytes of the pdf file 
    ModelAndView mav = new ModelAndView(); 
    mav.addObject("byteArray", bytes); 
    mav.setViewName("pdfByteArrayPrint"); 
    return mav; 
} 
相關問題