Upload PDF file to mysql BLOB by using java.sql.PreparedStatement without corruption

回眸只為那壹抹淺笑 提交于 2019-12-06 08:09:44

问题


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'


回答1:


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());



回答2:


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

and don't initialize length i.e instead of

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

just write

int length;

then it downloads file successfully .. enjoy :)



来源:https://stackoverflow.com/questions/11238927/upload-pdf-file-to-mysql-blob-by-using-java-sql-preparedstatement-without-corrup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!