怎么用jsp从mysql数据库中提取图片

怎么用jsp从mysql数据库中提取图片,第1张

1.去文件名 也就是你的图片实际上是存在你的项目中的 读的只是你的文件名加上路径就行了,

2.添加图片的时候,以IO的形式,把图片真真读到数据库,取的时候,取出来,进行一次转换,显示图片。

我知道的就是这两种思路 希望对你有用!

1 mysql存储大容量的二进制文件的格式是longblob ,其实除了图片还可以存别的

CREATE TABLE`abc`.`images` (

`name` varchar(10) NOT NULL,

`changdu` int(10) unsigned NOT NULL,

`content` longblob NOT NULL,

PRIMARY KEY (`name`)

)

ENGINE=InnoDB DEFAULT CHARSET=utf8

2 要向数据库存储二进制的文件一定要把要存储的数据转换成二进制流

废话就不多说了,大家看看代码很容易明白,先来看一个app程序,当然首先您要在数据库中先建立一个用于保存图片的表和相应的列,

数据格式为blob

package com.lizhe

import java.io.*

import java.sql.*

public class PutImg {

public void putimg() {

try {

Class.forName("org.gjt.mm.mysql.Driver").newInstance()

String url = "jdbc:mysql://localhost/img?user=root&password=root&useUnicode=true&characterEncoding=gbk"

Connection conn = DriverManager.getConnection(url)

Statement stmt = conn.createStatement()

//stmt.execute("insert into imgt (id) values (5)")

stmt.close()

PreparedStatement pstmt = null

String sql = ""

File file = new File("c:\\blog.jpg")

InputStream photoStream = new FileInputStream(file)

//sql = " UPDATE imgt SET img = ? "

sql = "INSERT INTO imgtable(img) VALUES (?)"

pstmt = conn.prepareStatement(sql)

pstmt.setBinaryStream(1, photoStream, (int) file.length())

pstmt.executeUpdate()

pstmt.close()

conn.close()

} catch (Exception e) {

e.printStackTrace()

}

}

public static void main(String args[]){

PutImg pi=new PutImg()

pi.putimg()

}

}

InputStream photoStream = new FileInputStream(file)

可以很清楚的看到我们首先把一个图片文件(当然也可以是别的什么文件)转换成了一个二进制输入流

pstmt.setBinaryStream(1, photoStream, (int) file.length())

这个方法建议大家去查一下API文档,第一个参数是通配符位置没的说,第二个参数是流,这和以往的string类型的参数不太一样,

我刚看到的时候也觉得豁然开朗了,但是到这里还没完,不同于以往的字符串参数,这里我们还需要第三个参数来设置这个流的长度,

这里也就是这个文件的长度,导出数据库中的sql,一切都清楚了

INSERT INTO `m_diy` VALUES (2,?\0 JFIF\0 \0H\0H\0\0?? Exif\0\0MM\0*\0\0\0 \0\0 \0\0\0 \0 \0\0\0 \0\0\0 \0\0\0b

\0 \0\0\0 \0\0\0j (\0 \0\0\0 \0 \0\0 1\0 \0\0\0 \0\0\0r 2\0 \0\0\0 \0\0\0?i\0 \0\0\0 \0\0\0\0\0\0\0\0\0H\0\0\0

\0\0\0H\0\0\0 Adobe Photoshop CS Windows\02007:03:18 23:08:15\0\0\0\0\0 ?\0 \0\0\0 ??\0\0?\0 \0\0\0 \0\0\0? \0

........等等

其实就是将文件先转换成了二进制的流,然后插入到了sql语言中,向数据库写入了很长很长的一段sql语句

然后我们再来写一个app程序将这个文件读出来,存储成一个图片文件

package com.lizhe

import java.io.*

import java.sql.*

class GetImg {

private static final String URL = "jdbc:mysql://localhost/img?user=root&password=root&useUnicode=true&characterEncoding=gbk"

private Connection conn = null

private PreparedStatement pstmt = null

private ResultSet rs = null

private File file = null

public void blobRead(String outfile, int picID) throws Exception {

FileOutputStream fos = null

InputStream is = null

byte[] Buffer = new byte[4096]

try {

Class.forName("org.gjt.mm.mysql.Driver").newInstance()

conn = DriverManager.getConnection(URL)

pstmt = conn.prepareStatement("select img from imgt where id=?")

pstmt.setInt(1, picID)// 传入要取的图片的ID

rs = pstmt.executeQuery()

rs.next()

file = new File(outfile)

if (!file.exists()) {

file.createNewFile()// 如果文件不存在,则创建

}

fos = new FileOutputStream(file)

is = rs.getBinaryStream("img")

int size = 0

while ((size = is.read(Buffer)) != -1) {

// System.out.println(size)

fos.write(Buffer, 0, size)

}

} catch (Exception e) {

System.out.println( e.getMessage())

} finally {

// 关闭用到的资源

fos.close()

rs.close()

pstmt.close()

conn.close()

}

}

public static void main(String[] args) {

try {

GetImg gi=new GetImg()

gi.blobRead("c:/getimgs/1.jpg", 5)

} catch (Exception e) {

System.out.println("[Main func error: ]" + e.getMessage())

}

}

}

这里需要注意的是

is = rs.getBinaryStream("img")

img是数据库中相应的列名,其实和rs.getString()方法差不多,只不过这个方法是读取二进制流的

最后在帖两个bs系统上用的文件给大家参考

通过struts的action向数据库写入二进制图片

/*

* Generated by MyEclipse Struts

* Template path: templates/java/JavaClass.vtl

*/

package com.lizhe.struts.action

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.PreparedStatement

import java.sql.Statement

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

import org.apache.struts.action.Action

import org.apache.struts.action.ActionForm

import org.apache.struts.action.ActionForward

import org.apache.struts.action.ActionMapping

import org.apache.struts.upload.FormFile

import com.lizhe.struts.form.UpimgForm

/**

* MyEclipse Struts

* Creation date: 05-18-2007

*

* XDoclet definition:

* @struts.action path="/upimg" name="upimgForm" input="/userhomepage.jsp"

* @struts.action-forward name="userhome" path="/userhomepage.jsp" redirect="true" contextRelative="true"

*/

public class UpimgAction extends Action {

/*

* Generated Methods

*/

/**

* Method execute

* @param mapping

* @param form

* @param request

* @param response

* @return ActionForward

* @throws IOException

* @throws FileNotFoundException

*/

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {

UpimgForm upimgForm = (UpimgForm) form// TODO Auto-generated method stub

FormFile file=upimgForm.getFile()

InputStream is=file.getInputStream()

try {

Class.forName("org.gjt.mm.mysql.Driver").newInstance()

String url = "jdbc:mysql://localhost/blog?user=root&password=root&useUnicode=true&characterEncoding=gb2312"

Connection conn = DriverManager.getConnection(url)

Statement stmt = conn.createStatement()

//stmt.execute("insert into img (id) values (5)")

stmt.close()

PreparedStatement pstmt = null

String sql = ""

//File file = new File("c:\\blog.jpg")

//InputStream photoStream = new FileInputStream(file)

//sql = " UPDATE imgt SET img = ? "

sql = "INSERT INTO img (img) VALUES (?)"

pstmt = conn.prepareStatement(sql)

pstmt.setBinaryStream(1, is, (int) file.getFileSize())

pstmt.executeUpdate()

pstmt.close()

conn.close()

} catch (Exception e) {

e.printStackTrace()

}

return mapping.findForward("userhomepage")

}

}

和app的方式几乎是一样的

第二个文件是通过jsp将数据库中的图片显示在页面上

这个有些不同

<%@ page contentType="text/htmlcharset=gb2312"%>

<%@ page import="java.sql.*" %>

<%@ page import="java.util.*"%>

<%@ page import="java.text.*"%>

<%@ page import="java.io.*"%>

<%@ page import="java.awt.*"%>

<html>

<body>

<%

Class.forName("org.gjt.mm.mysql.Driver").newInstance()

String url="jdbc:mysql://localhost/img?user=root&password=root"

Connection con = DriverManager.getConnection(url)

String sql = "select * fromimgt where id=5"

Statement stmt = con.createStatement()

ResultSet rs = stmt.executeQuery(sql)

if(rs.next()) {

InputStream in = rs.getBinaryStream("img")

ServletOutputStream op = response.getOutputStream()

int len

byte[] buf=new byte[1024]

while((len= in.read(buf))!=-1) {

op.write(buf, 0, len)

}

op.close()

in.close()

}

rs.close()

stmt.close()

con.close()

%>

</body>

</html>

mysql数据库里可以存储,图片的相对路径,还有每个图片要有唯一的ID,在数据库里,可以设置成自动编号。楼主实在不懂,留一邮箱,我做个例子给你发过去。

具体代码

<%@ page contentType="text/htmlcharset=utf-8" language="java" import="java.sql.*" errorPage="" %>

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<title>无标题文档</title>

</head>

<body>

<p>

<table border="1">

<tr>

<td>图片Num</td>

<td>图片</td>

</tr>

<%

Connection conn = null

Statement stmt = null

ResultSet rs = null

request.setCharacterEncoding("utf-8")

String uri = "jdbc:mysql://localhost:3306/test"//使用的是test数据库

String sql = "select picNum from pic "//我建图片表 pic

try{

Class.forName("com.mysql.jdbc.Driver")

}catch(Exception e){

out.print(e)

}

try{

conn = DriverManager.getConnection(uri,"root","soft")//我的用户名是 root ,密码 是 soft 根据你的需要 更改

stmt = conn.createStatement()

rs = stmt.executeQuery(sql)

while(rs.next()){

%>

<tr>

<td><%=rs.getString("picNum")%></td>

<td><img src="tupian/<%=rs.getString("picNum")%>"></td>

</tr>

<%

}

}catch(Exception e){

out.print(e)

}

%>

</table>

</body>

</html>

附录:sql脚本

use test

create table pic(

id int primary key auto_increment,

picNum varchar(10) unique

)

insert into pic(picNum) values('1.jpg')

insert into pic(picNum) values('2.jpg')

insert into pic(picNum) values('3.jpg')

insert into pic(picNum) values('4.jpg')

insert into pic(picNum) values('5.jpg')

insert into pic(picNum) values('6.jpg')

insert into pic(picNum) values('7.jpg')


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5943035.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-09
下一篇 2023-03-09

发表评论

登录后才能评论

评论列表(0条)

保存