数据库是oracle,字段是blob,代码语言是java,上传的可以是图片也可以是其他大文件,显示在浏览器里和保存在硬盘上不写在这篇文章里,写在下篇里
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFileChooser;
import oracle.jdbc.driver.OracleConnection;
public class Write
{
public static void main(String[] args)
{
try {
Writewatdb = new Write();
watdb.sendToDb();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Connection conn;
Statement stmt;
ResultSet rs;
int bufferSize;
public Write() throws SQLException, ClassNotFoundException
{
String connectString;
Class.forName("oracle.jdbc.driver.OracleDriver");
connectString = "jdbc:oracle:thin:@192.168.1.134:1521:zhpt";
conn = (OracleConnection)
DriverManager.getConnection(connectString, "dzjc","dzjc");
stmt = conn.createStatement();
}
public void sendToDb()
{
int amount = 0;
OutputStream out = null;
BufferedInputStream in = null;
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
pathname = chooser.getSelectedFile().getAbsolutePath();
name = chooser.getSelectedFile().getName();
chooser = null;
}
else
{
System.out.println("没有找到文件!");
System.out.println("程序非正常结束...");
return;
}
try
{
conn.setAutoCommit(false);
stmt.executeUpdate("insert into dzjc_img(img) values (empty_blob())");
rs = stmt.executeQuery("select img from dzjc_img for update");
if (rs.next())
{
Blob blob = rs.getBlob("img");
out = ( (oracle.sql.BLOB) blob).getBinaryOutputStream();
bufferSize = ( (oracle.sql.BLOB) blob).getBufferSize();
in = new BufferedInputStream(new FileInputStream(pathname), bufferSize);
byte[] b = new byte[bufferSize];
int count = in.read(b, 0, bufferSize);
while (count != -1)
{
out.write(b, 0, count);
amount += count;
System.out.println("处理了" + amount + "字节.");
count = in.read(b, 0, bufferSize);
System.out.println("处理了" + amount + "字节,成功.");
}
out.close();
out = null;
in.close();
in = null;
conn.commit();
}
}
catch (Exception e)
{
e.printStackTrace();
try
{
conn.rollback();
}
catch (Exception ignored) {}
}
finally
{
if (out!=null) try{out.close();} catch(Exception igored){}
if (in!=null) try{in.close();} catch(Exception igored){}
}
}
}
可直接运行
数据库就自己建吧,建个类型为blob型的就行了