我正在尝试将pdf文件上传到我的数据库并尝试下载相同的文件但我无法在文件下载后打开该文件我收到错误,指出文件类型不受支持。 这是文件上传的代码。
package itext;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.PreparedStatement;
public class FileUpload {
public static void fileupload() throws FileNotFoundException{
String inFile="D:/Eclipse Java/myown.pdf";
FileInputStream io = new FileInputStream(inFile);
byte[] pdfData = new byte[(int) inFile.length()];
DataInputStream dis;
try {
dis = new DataInputStream(new FileInputStream(inFile));
dis.readFully(pdfData); // read from file into byte[] array
dis.close();
Connection dbConnection;
String myConnectionString =
"jdbc:mysql://******/*****";
dbConnection = DriverManager.getConnection(myConnectionString, "****", "****");
PreparedStatement ps = (PreparedStatement) dbConnection.prepareStatement("INSERT INTO Form_BL (AppID,Form) VALUES (?,?)");
ps.setString(1, "1");
ps.setBytes(2, pdfData); // byte[] array
ps.executeUpdate();
ps.setBinaryStream(1, (InputStream)dis,(int)inFile.length());
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是下载代码
package itext;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.Blob;
import com.mysql.jdbc.PreparedStatement;
public class FileDownload {
public static void filedownload(){
Connection dbConnection;
ResultSet rs;
String myConnectionString =
"jdbc:mysql://*****/*****";
try {
dbConnection = DriverManager.getConnection(myConnectionString, "****", "****");
PreparedStatement ps=(PreparedStatement) dbConnection.prepareStatement("select AppID from Form_BL where AppID='1' ");
rs=ps.executeQuery();
rs.next();
java.sql.Blob b=rs.getBlob(1);
byte barr[]=new byte[(int)b.length()];//an array is created but contains no data
barr=b.getBytes(1,(int)b.length());
FileOutputStream fout=new FileOutputStream("D:/download.pdf");
fout.write(barr);
fout.close();
System.out.println("ok");
dbConnection.close();
ps.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
我正在使用以下链接的引用来执行此操作。 Upload PDF file to mysql BLOB by using java.sql.PreparedStatement without corruption。提前致谢
答案 0 :(得分:0)
看起来将二进制内容(PDF文件)保存到BLOB中的代码很好。但是当你试图恢复PDF内容时,看起来你有些麻烦。
你可能想尝试一下:
Blob b = rs.getBlob(1);
InputStream is = b.getBinaryStream();
FileOutputStream fos = new FileOutputStream("D:/download.pdf");
int i = 0;
// IMPORTANT: Remember to handle/close all I/O properly
while ((i = is.read()) != -1) {
fos.write(b);
}