Java 从db2 blob字段检索p7m文件
我需要检索存储在blob字段中的p7m pdf文件,并通过指向特定url将其直接下载 现在我使用下面的代码来检索和发布pdf,但是打开用查看数字签名工具保存的文件,签名无效,pdf似乎已损坏Java 从db2 blob字段检索p7m文件,java,pdf,servlets,Java,Pdf,Servlets,我需要检索存储在blob字段中的p7m pdf文件,并通过指向特定url将其直接下载 现在我使用下面的代码来检索和发布pdf,但是打开用查看数字签名工具保存的文件,签名无效,pdf似乎已损坏 public byte[] getPdfOrdini(String xxx, String tipo) throws Exception, SQLException { Blob pdf; byte[] pdfData = null; Connection conn = new te
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
{
}
}
%>
非常感谢您的帮助。您的两个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();
谢谢你的建议,但我还是得到了同样的结果。我认为这是jsp中的文件生成问题,但我不明白问题出在哪里。您确定数据正确存储在数据库中吗?是的,在我的webapp中,我还提供了一个jsp,用于通过浏览器以可视化模式显示pdf文件,并且pdf已正确打开。问题是生成一个可下载的文件以检查数字签名信息。请参阅我编辑的答案:您正在将数据写入浏览器吗?很抱歉,对于这个问题,out object的写入方法希望第一个参数为char数组,但我有byte数组。