1

我需要检索存储在 blob 字段中的 p7m pdf 文件,并通过指向特定的 url 将其直接下载。

现在我正在使用以下代码检索和发布 pdf,但是打开使用查看数字签名工具保存的文件,签名无效并且 pdf 似乎已损坏。

public byte[] getPdfOrdini(String xxx, String tipo) throws Exception, SQLException {
    Blob pdf;
    byte[] pdfData = null;
    Connection conn = new test().getConnectionOrdini();
    PreparedStatement pstmt = null;

    // Query
    if(tipo.equalsIgnoreCase("pnf"))
        pstmt = conn.prepareStatement("Select ... From .. Where ..");
    if(tipo.equalsIgnoreCase("pf"))
        pstmt = conn.prepareStatement("Select ... From .. Where .. = ?");
    pstmt.setString(1, xxx);
    ResultSet rset = pstmt.executeQuery();

    if(tipo.equalsIgnoreCase("pnf")){

        while (rset.next()) {
            pdf = rset.getBlob(1);
            pdfData = pdf.getBytes(1, (int) pdf.length());
        }

        //System.out.println("dimensione blob --> " + pdfData.length);
    }else{
        while (rset.next()) {
            pdf = rset.getBlob(1);
            pdfData = pdf.getBytes(1, (int) pdf.length());
        }
    }
    rset.close();
    pstmt.close();

    return pdfData;
}

以及用于发布 pdf 以供下载的代码:

<jsp:useBean id="PDF" class="pdf.test" scope="session" />
<%
Connection conn = null;

if ( request.getParameter("protocollo") != null )
{

String protocollo = request.getParameter("xxx") ;
String tipo = request.getParameter("type");   

try
{  
   String downloadFileName = "O" + xxx + ".pdf.p7m";
   conn = new pdf.test().getConnection();
   conn.setAutoCommit (false);  

   // get the image from the database
   byte[] pdfData = PDF.getPdfOrdini(xxx, tipo);   
   // display the image

   File pdf = new File(downloadFileName);
   FileOutputStream fos = new FileOutputStream(pdf);
   fos.write(pdfData);
   fos.flush();
   fos.close();

   response.setContentType( "application/x-download" );
   response.setHeader( "Content-Disposition", "attachment; filename=" + downloadFileName );
   conn.close();
}
catch (IllegalStateException il){
}
catch (Exception e)
{
  e.printStackTrace();
  throw e;
}
finally
{

}  
}
%>

任何帮助表示赞赏。

4

1 回答 1

0

您的两个 while 阅读块是相同的,但无论如何它应该可以工作。
你可以试试这个,在 DB2 上一直为我工作:

byte[] pdfData = null;
ResultSet rset = pstmt.executeQuery();
if (rset.next())
{
  pdfData = rset.getBytes(1);
}
conn.close();
return pdfData;

补充:
接下来的事情是,我没有看到您在 JSP 中将数据写入浏览器。
像这样的东西:

byte[] pdfData = PDF.getPdfOrdini(xxx, tipo);
char[] data = new char[pdfData.length];
for (int i = 0; i < pdfData.length; i++) {
    data[i] = (char) pdfData[i];
    }
response.setContentType( "application/x-download" );
response.setHeader( "Content-Disposition", "attachment; filename=" + downloadFileName );
response.setHeader("Content-length", Integer.toString(data.length));
out.write( data, 0, data.length);
out.flush();
于 2012-12-03T10:14:47.217 回答