blob PDF java,使用java.sql.PreparedStatement将PDF文件上传到mysql BLOB而不会损坏

I tried to uplad a pdf file using java.sql.PreparedStatement to mysql Blob field using the following code.

File inFile = new File("Path+BLOCK.pdf");

byte[] b = new byte[(int)inFile.length()];

PreparedStatement psmnt = (PreparedStatement)

con.prepareStatement("INSERT INTO

2012DOC (SRNO,DOCUMENT)

VALUES (?,?)"

); //con is java.sql.Connection object

psmnt.setString(1, "1200021");

psmnt.setBytes(2, b);

psmnt.executeUpdate();

This code executes without error and database shows blob content, but when I try to retrieve the file using the below code it gives a corrupt file which doesn't open.

ResultSet rs=con.Execute("SELECT DOCUMENT FROM 2012DOC");

rs.next();

response.setContentType("application/pdf");

response.setHeader("Content-Disposition", "attachment; filename=kjsahkjd.pdf");

java.sql.Blob blob = rs.getBlob("DOCUMENT");

ServletOutputStream servletOutputStream = response.getOutputStream();

InputStream in = blob.getBinaryStream();

int length = (int) blob.length();

int bufferSize = 1024;

byte[] buffer = new byte[bufferSize];

while ((length = in.read(buffer)) != -1) {

servletOutputStream.write(buffer, 0, length);

}

in.close();

servletOutputStream.flush();

servletOutputStream.close();

It outputs the file with same size as the original,but the file doesn't open.

The pdf reader is fired but cannot open the file and gives an error 'the file was either damaged or not supported file type'

解决方案

Ahhh...After a little debugging I found the code that uploads is troublesome, and finally got the right way to do it.

Here is what I did...I'm posting it so that others with same problem can solve it

After Converting the java.io.File to java.io.FileInputStream

FileInputStream io = new FileInputStream(inFile);

Set the BLOB field using psmnt.setBinaryStream()

psmnt.setBinaryStream(3, (InputStream)io,(int)inFile.length());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值