使用java.sql.PreparedStatement将PDF文件上传到mysql BLOB而不会损坏 [英] Upload PDF file to mysql BLOB by using java.sql.PreparedStatement without corruption
问题描述
我尝试使用以下代码使用 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();
此代码执行时没有错误,数据库显示blob内容,但是当我尝试使用在代码下面它给出了一个无法打开的损坏文件。
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();
它输出的文件大小与原文相同,但文件无法打开。
pdf
读取器被触发但无法打开文件并发出错误'文件已损坏或不支持文件类型'
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
转换后 java.io.File
to java.io.FileInputStream
FileInputStream io = new FileInputStream(inFile);
使用 psmnt.setBinaryStream()$ c $设置BLOB字段c>
psmnt.setBinaryStream(3, (InputStream)io,(int)inFile.length());
这篇关于使用java.sql.PreparedStatement将PDF文件上传到mysql BLOB而不会损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!