2017-02-13 51 views
0

我有一個jsp頁面,帶有一個按鈕,該鏈接在一個servlet上,並創建一個PDF文件作爲響應的流。JSP Servlet響應pdf到Jquery

protected void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException, IOException { 
    path = request.getServletContext().getRealPath("/"); 
    String pdfFileName = "foo.pdf"; 
    String contextPath = getServletContext().getRealPath(File.separator); 
    File pdfFile = new File(path + pdfFileName); 

    response.setContentType("application/pdf"); 
    response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName); 
    response.setContentLength((int) pdfFile.length()); 

    FileInputStream fileInputStream = new FileInputStream(pdfFile); 
    OutputStream responseOutputStream = response.getOutputStream(); 
    int bytes; 
    while ((bytes = fileInputStream.read()) != -1) { 
     responseOutputStream.write(bytes); 
    } 


} 

的jQuery是

$(document).ready(function() { 
    $(".getpdfbutton").click(function(){ 
     var currentRow=$(this).closest("tr"); 
     var col1=currentRow.find("td:eq(0)").html(); 
     var data3=col1; 
     alert(data3); 
     $.get("PDFerzeugen",{Spass:data3}, function(data) { 
      /* window.location = data; */ 
      alert(data); 
     }); 
    }); 

我得到的數據respons爲base64,我怎麼能下載pdf格式的文件?

+1

[下載文件使用JavaScript/jQuery的]的可能的複製(http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery) – BackSlash

+0

你的問題是什麼?你的pdf沒有顯示,或者你想下載它? – Mike

+0

看看這個:[link] http://stackoverflow.com/questions/26332467/add-image-into-div-and-convert-base64-string-into-thumbnail-using-jquery [鏈接] – Vish

回答

0

我解決了它在這個腳本

function SaveToDisk(fileURL, fileName) { 
    // for non-IE 
    if (!window.ActiveXObject) { 
     var save = document.createElement('a'); 
     save.href = fileURL; 
     save.target = '_blank'; 
     save.download = fileName || 'unknown'; 

     var evt = new MouseEvent('click', { 
      'view': window, 
      'bubbles': true, 
      'cancelable': false 
     }); 
     save.dispatchEvent(evt); 

     (window.URL || window.webkitURL).revokeObjectURL(save.href); 
    } 

    // for IE < 11 
    else if (!! window.ActiveXObject && document.execCommand)  { 
     var _window = window.open(fileURL, '_blank'); 
     _window.document.close(); 
     _window.document.execCommand('SaveAs', true, fileName || fileURL) 
     _window.close(); 
    } 
};