2013-07-25 27 views
1

在我的應用程序中,json對象是在客戶端創建的。這個對象被髮布到一個HttpServlet,它根據POST數據創建一個pdf文件。如何使用Jquery從httpServlet下載文件?

該文件發回給用戶。調用succes函數,並記錄流數據。然而,我想要下載文件。

如何實現這一目標?

我的客戶機側代碼:

$(document).ready(function() { 
// when the print button is clicked 
$('#exportButton').click(function() { 

    var tableIdx = performanceDetailTableController.getTableIdx(); 

    var allData = { 
     "shipTable1":{ 
      "rows":[ 
       { "latitude":"12323","longitude":"213213"}, 
       { "latitude":"213213","longitude":"543543"} 
      ]}, 
     "shipTable2":{ 
      "rows":[ 
       { "latitude":"12323", "longitude":"213213"}, 
       { "latitude":"213213","longitude":"543543"} 
      ]} 
     } 

    var postData = JSON.stringify(allData); 

    $.ajax({ 
     type : "POST", 
     url : 'pdfServlet', 
     contentType: "application/json; charset=utf-8", 
     data : postData, 
        async : false, 
     success : function(data) { 
      alert("got some data"); 
      console.log(data); 
     }, 
    }); 
}); 

});

並且servlet創建文件:

%PDF-1.4 
% 
4 0 obj 
<< 
/Producer (Apache FOP Version SVN branches/fop-0_95) 
/CreationDate (D:20130725162007+02'00') 
>> 
endobj 
5 0 obj 
<< 
    /N 3 
    /Length 11 0 R 
    /Filter /FlateDecode 
>> 
stream 
xwTSϽ7PhRHH.*1 J 

* 我的解決方案:

@Override 
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { 

    // get the json content 
    StringBuffer jsonContent = getPostedContent(request); 

    log.info(jsonContent.toString()); 

    // convert json to pojo's 
    Tables tables = getTablesFromString(jsonContent); 

    // create a xml stream 
    ByteArrayOutputStream xml = new XmlConverter().getXMLSource(tables); 

    // put the xml on the request 
    request = setXmlOnRequest(request, xml); 

    // create pdf data of the pdf-able xml content 
    ByteArrayOutputStream pdf = new PdfHandler().createPdfDataStream(request); 

    // response = createResponseheaders(response, request); 
    response.setContentType("application/pdf"); 
    response.setContentLength(pdf.size()); 
    response.setHeader("Content-disposition", "attachment; filename=test.pdf"); 
    response.setCharacterEncoding("utf-8"); 
    response.getOutputStream().write(pdf.toByteArray()); 

    //close the streams 
    pdf.close(); 
    response.getOutputStream().close(); 
} 

日誌中的輸出中*

看到http://www.particletree.com/notebook/ajax-file-download-or-not/的指針

我創建了一個表單隱藏字段:

 <button id="exportButton">export</button> 
    <form id="exportForm" method="post" action="pdfServlet"> 
     <input type="hidden" value="empty" id="pdf_data" name="pdf_data" /> 
    </form> 

比我改變了我的jQuery POST數據控制器:

$('#exportButton').click(function() { 

    var tableIdx = performanceDetailTableController.getTableIdx(); 

     var allData = { 
     "shipTable1":{ 
      "rows":[ 
       { "latitude":"12323","longitude":"213213"}, 
       { "latitude":"213213","longitude":"543543"} 
      ]}, 
     "shipTable2":{ 
      "rows":[ 
       { "latitude":"12323", "longitude":"213213"}, 
       { "latitude":"213213","longitude":"543543"} 
      ]} 
     } 



    var postData = JSON.stringify(allData); 

    // put the data on the hidden form field in the export form 
    $('#pdf_data').val(postData); 

    // and submit the form 
    $('#exportForm').submit(); 

}); 

所以現在當我點擊導出按鈕,在表單中的隱藏字段獲得發佈的數據,並將數據發佈爲www-form編碼。

這樣servlet可以處理請求並將文件下載到客戶端。

+0

你不能用ajax強制文件下載。 –

+0

Ajax響應不允許下載文件。 – NINCOMPOOP

回答

3

你不能用ajax下載文件。 JavaScript有明顯的安全原因,沒有任何工具可以觸發與JavaScript上下文中任意檢索/生成的內容進行對話。如果可能的話,萬維網看起來會非常不同。

如果你堅持使用JS/jQuery,那麼你需要發送一個synchronus GET請求。您可以使用window.location(您只需要將doPost()重命名爲doGet())。

window.location = 'pdfServlet?param1=value1&param2=value2'; 

另外,剛剛扔掉所有不必要的JS/jQuery和只使用純HTML <form action="pdfServlet" method="post"><input type="submit">。額外的好處是它可以在JS禁用的瀏覽器中工作。

如果你唯一的理由抓住ajax實際上是一個天真的嘗試,以避免頁面刷新,那麼我可以告訴你,如果響應有一個Content-Disposition: attachment標題,這真的不會發生。所以那部分已經安全了。

+0

他的請求是POST。必須隨時隨地玩。 –

+1

+1不太明顯。 OP可以改變它來使用表單。 –

+0

所以基本上我會讓用戶發佈其內容,創建一個PDF文件,並將其寫入服務器上的磁盤,並提供給用戶一個鏈接,他可以從中下載文件? – jorrebor