无法设法通过Servlet下载从BLOB检索的PDF

时间:2018-08-17 14:22:39

标签: javascript java pdf blob

我环顾四周,尝试了一些看到的解决方案,但似乎没有任何效果。

这是我的情况:

我在Oracle数据库中将PDF文件存储为BLOB。 在我的后端,我打电话给我的服务以便下载该pdf文件(在我的实体中,该pdf文件是byte[]),

@GET
@Path("/downloadpdf")
@Produces("application/pdf")
public HttpServletResponse downloadPdf(@Context HttpServletRequest request, @Context HttpServletResponse response) {
    try {
        UserGuideJpaService userGuideService = new UserGuideJpaServiceImpl();
        HashMap<String, Object> result = userGuideService.getPdfGuide();
        if ("0".equals(result.get("returnCode"))) {
            UserGuide userGuide = (userGuide) result.get("userGuide");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-control", "private");
            response.setDateHeader("Expires", 0);
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\"APP - User Guide.pdf\"");

            byte[] pdf = userGuide.getPdf();

            if (pdf != null) {
                response.setContentLength(pdf.length);
                ServletOutputStream out = response.getOutputStream();
                out.write(pdf);
                out.flush();
                out.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

回到我的前端,我有这个:

注意::这就是我的response.data的样子(是一个字符串):

  

%PDF-1.4%����

     

8 0 obj << / Type / Page / Resources << / ProcSet [/ PDF / Text] /字体   4 0 R /阴影6 0 R / ExtGState 7 0 R

     
    
      

/ MediaBox [0 0 595.28 864.00] / Contents 9 0 R / Parent 10 0 R >> endobj

    
  
     

9 0 obj << / Length 1679 / Filter [/ FlateDecode] >>流   x��X�n7��?]�84��aw�= I.Jrv %% @@ Q.as +.��r%% E _-%。 {x�|�    ��1������o�Oo������{����ߌj��bCN_3�81���{��̭]�9����rXU��e��T ]WV����m�q5| \5�a''Ꞽ����T0n〜''O�X��9�#〜+�b�5��7���9。 ������)�R/f�5xF���5�WW���eA���lr}A.'�7Ej�iƳ���]���。 �+f�ܦ�UT�<��1��,ZrE3�s��4�bzU,f�4�̎    �U�*7�̋��vN΋���4��'�䌜��^�Nf#!��〜2��\ G +�_�,��b<�2��/�� ��WIU��V�2%��B����{Z��d�H�̀R�.g%@�����0Ln)�9...

和javascript端:

$scope.downloadPdf = function() {
  APIClientService.downloadPdf().then(function(response) {
    // #1
    var URL, blob, downloadLink, downloadUrl;
    downloadLink = document.createElement('a');
    downloadLink.target = '_blank';
    downloadLink.download = 'APP - User Guide.pdf';
    blob = new Blob([response.data], {
      type: 'application/pdf'
    });
    URL = window.URL || window.webkitURL;
    downloadUrl = URL.createObjectURL(blob);
    downloadLink.href = downloadUrl;
    document.body.append(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
    URL.revokeObjectURL(downloadUrl);
    // # 2
    window.open("data:application/pdf," + encodeURI(response.data));
    // # 3
    window.open("data:application/pdf," + escape(response.data));
  });
};

但是,这不会下载文件,甚至不会打开文件。

我非常确定pdf在后端是正确的,因为我在使用时设法得到了它:

    OutputStream out = new FileOutputStream("Test.pdf");
    out.write(pdf);
    out.close();

然后如何从浏览器下载pdf表格?或者至少打开它?

编辑:这是APIClientService中的方法:

({
  downloadPdf: function() {
    return $http({
      method: 'GET',
      url: this.baseUrl + "/downloadpdf"
    });
  }
});

1 个答案:

答案 0 :(得分:1)

默认情况下,ajax请求会将您的响应视为文本,这将导致非文本文件出现问题。

为防止这种情况,请向您的请求中添加一个二进制responseType,例如

function queryDb(query){
  return new Promise( ( resolve, reject ) => {
      connection.query(query, (err, result)=>{
          if (err){
              return reject( err );
          }
          resolve( result );
      });
  })
}