如何上传文件到数据库?
2个回答
展开全部
文件上传到数据库请参考以下示例:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page language="java" import="java.sql.*" %>
<%/////连接数据库
java.sql.Connection conn;
java.sql.Statement stmt;
java.sql.ResultSet rs1;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:dababasename");///数据源
stmt=conn.createStatement();
%>
<%
String sqlin="insert into drawing values ;
File file = new File("c:/z.jpg");
long l1=file.length();
int l2=(int)l1;
FileInputStream is = new FileInputStream(file);
InputStream fis=(InputStream)is;
PreparedStatement ps = conn.prepareStatement("insert into images values (?,?)");
ps.setString(1,file.getName());
ps.setBinaryStream(2,fis,file.length());
ps.executeUpdate();
ps.close();
fis.close();
//将图片从数据库中提取,进行显示
//drawing字段为IMAGE类型
stmt = conn.createStatement();
rs1 = stmt.executeQuery("SELECT * FROM drawing WHERE drawing_code ='0-515' and version=3");
if (rs1.next())
{
String dim_image = rs1.getString("file_name");
byte [] blocco = rs1.getBytes("drawing");
response.setContentType("image/jpeg");
ServletOutputStream op = response.getOutputStream();
for(int i=0;i<blocco.length;i++)
{
op.write(blocco[i]);
}
}
rs1.close();
%>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page language="java" import="java.sql.*" %>
<%/////连接数据库
java.sql.Connection conn;
java.sql.Statement stmt;
java.sql.ResultSet rs1;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:dababasename");///数据源
stmt=conn.createStatement();
%>
<%
String sqlin="insert into drawing values ;
File file = new File("c:/z.jpg");
long l1=file.length();
int l2=(int)l1;
FileInputStream is = new FileInputStream(file);
InputStream fis=(InputStream)is;
PreparedStatement ps = conn.prepareStatement("insert into images values (?,?)");
ps.setString(1,file.getName());
ps.setBinaryStream(2,fis,file.length());
ps.executeUpdate();
ps.close();
fis.close();
//将图片从数据库中提取,进行显示
//drawing字段为IMAGE类型
stmt = conn.createStatement();
rs1 = stmt.executeQuery("SELECT * FROM drawing WHERE drawing_code ='0-515' and version=3");
if (rs1.next())
{
String dim_image = rs1.getString("file_name");
byte [] blocco = rs1.getBytes("drawing");
response.setContentType("image/jpeg");
ServletOutputStream op = response.getOutputStream();
for(int i=0;i<blocco.length;i++)
{
op.write(blocco[i]);
}
}
rs1.close();
%>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |