jsp mysql图片轮播_Jsp向MySql数据库中写入图片文件

本文介绍如何使用JSP将图片文件存储到MySQL数据库中,并提供了一个测试示例来验证写入和读取的过程。文章还讨论了将图片直接存储在数据库可能带来的性能问题,建议将图片保存在服务器上,仅在数据库中存储路径作为更好的实践。
摘要由CSDN通过智能技术生成

一、先在数据库建这样一张表,下面的这些代码对任何数据库都通用,只要支持blob类型的。

SQL>create   table   image(id  int,content  varchar(200),image   blob);

二、

testimage.html文件内容如下:

Image   File  

我们在Form的action里定义了一个动作testimage.jsp,它的内容如下:

String  url="jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding=8859_1";

//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改

Connection   conn=   DriverManager.getConnection(url);

String  content=request.getParameter("content");

String  filename=request.getParameter("image");

FileInputStream   str=new   FileInputStream(filename);

String   sql="insert   into  test(id,content,image)   values(1,?,?)";

PreparedStatement  pstmt=dbconn.conn.prepareStatement(sql);

pstmt.setString(1,content);

pstmt.setBinaryStream(2,str,str.available());

pstmt.execute();

out.println("Success,You  Have   Insert   an  Image   Successfully");

%>

下面我写一个测试image输出的例子看我们上面程序写的对不对,testimageout.jsp的内容如下:

String  url="jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding=8859_1";

//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改

Connection   conn=   DriverManager.getConnection(url);

String   sql   =  "select   image   from  test   where   id=1";

Statement   stmt=null;

ResultSet   rs=null;

try{

stmt=conn.createStatement();

rs=stmt.executeQuery(sql);

}catch(SQLException   e){}

try   {

while(rs.next())   {

res.setContentType("image/jpeg");

ServletOutputStream   sout   =  response.getOutputStream();

InputStream   in   =  rs.getBinaryStream(1);

byte   b[]   =  new   byte[0x7a120];

for(int   i   =  in.read(b);   i   !=  -1;)

{

sout.write(b);

in.read(b);

}

sout.flush();

sout.close();

}

}

catch(Exception  e){System.out.println(e);}

%>

你运行这个程序,你就会看到刚才你写入美丽的图片就会显示在你面前。怎么样,用jsp来试试。

这种方法把图片写到数据库中会使数据库在短时间内容量飞涨,会影响性能的,另外一种做法将图片存上传到服务器上,

在数据库里只存放图片的路径,这是一个很好的方法。我建议大家采取后面一种方法。

来源:行足迹旅游转载请注明

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值