图片存到数据库,并在页面读取出来

(一)将图片存储到数据库中(注:本文讨论的数据库是sql server) 
在sql server专门有存储图片的数据类型image,我们可以很方便的使用,我比较习惯根据代码来讲解……

[c-sharp] view plaincopyprint?#region 执行sql语句存储图片   
/// <summary>   
/// 执行sql语句存储图片   
/// </summary>   
/// <param name="ProcName">sql语句</param>   
/// <param name="prams">参数</param>   
public static void StoreImage(string ProcName, SqlParameter[] prams)  
{  
    try  
    {  
        SqlCommand cmd = CreateCommand(ProcName, prams, CommandType.Text);  
        cmd.ExecuteNonQuery();  
    }  
    finally  
    {  
        CloseConn();  
    }  
}  
#endregion  
 
#region 将图片转换为byte数组   
/// <summary>   
/// 将图片转换为byte数组   
/// </summary>   
/// <param name="strFullPath">图片的完整路径</param>   
/// <returns>byte[]</returns>   
public static byte[] ImageToByte(string strFullPath)  
{  
    byte[] imagebyte = null;  
    FileStream fs = new FileStream(strFullPath, FileMode.Open);  
    BinaryReader br = new BinaryReader(fs);  
    imagebyte = br.ReadBytes((int)fs.Length);  
    return (imagebyte);  
}  
#endregion  
    #region 执行sql语句存储图片
    /// <summary>
    /// 执行sql语句存储图片
    /// </summary>
    /// <param name="ProcName">sql语句</param>
    /// <param name="prams">参数</param>
    public static void StoreImage(string ProcName, SqlParameter[] prams)
    {
        try
        {
            SqlCommand cmd = CreateCommand(ProcName, prams, CommandType.Text);
            cmd.ExecuteNonQuery();
        }
        finally
        {
            CloseConn();
        }
    }
    #endregion

    #region 将图片转换为byte数组
    /// <summary>
    /// 将图片转换为byte数组
    /// </summary>
    /// <param name="strFullPath">图片的完整路径</param>
    /// <returns>byte[]</returns>
    public static byte[] ImageToByte(string strFullPath)
    {
        byte[] imagebyte = null;
        FileStream fs = new FileStream(strFullPath, FileMode.Open);
        BinaryReader br = new BinaryReader(fs);
        imagebyte = br.ReadBytes((int)fs.Length);
        return (imagebyte);
    }
    #endregion 

函数StoreImage中的ProcName是存储图片的sql语句,prams是一个数组,用来存储插入语句需要使用的参数,我这样做主要是因为把我函数写在公共类里面方便重复使用。insert into tb_class(classID,className,classImage) values(@classID,@className,@image),插入图片和插入其他数据没有什么不一样的,我们需要做的是就是在插入之前调用ImageToByte()函数将图片转换成byte数组,然后将byte[]存入数据库.

 

(二)将图片显示在网页上面

显示也可以说是成数据库中读取byte[]然后转换成图片,是存储的逆向过程。我们这里考虑2中情况下的图片读取:1.图片很大时,如4M; 2.需要将图片和文字混合显示。现在依次讲解

<1>step by step方式

[c-sharp] view plaincopyprint?#region 从数据库中读取图片,显示在当前页面   
    /// <summary>   
    /// 从数据库中读取图片,显示在当前页面(显示方式:step by step)   
    /// </summary>   
    /// <param name="ProcName">sql语句,查询字段为数据库中图片字段</param>   
    /// <param name="prams">参数</param>   
    /// <param name="Size">一次显示的字节数</param>   
    /// <param name="p">需要显示图片的页面,只能为this.page</param>   
    public static void GetImage(string ProcName, SqlParameter[] prams,int Size,Page p)  
    {  
        try  
        {  
            SqlCommand cmd = CreateCommand(ProcName, prams, CommandType.Text);  
            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);  
            byte[] bytes = null;  
            if (dr.Read())  
            {  
                int bufferSize = Size; //size of buffer.   
                bytes = new byte[bufferSize]; //the buffer of data.   
                long bytesRead; //the number of bytes read.   
                long readForm = 0; //the starting index.   
  
                //read the filed 100 bytes at a time.   
                do  
                {  
                    bytesRead = dr.GetBytes(0, readForm, bytes, 0, bufferSize);  
                    p.Response.BinaryWrite(bytes);  
                    readForm += bufferSize;  
                } while (bytesRead == bufferSize);  
            }  
            dr.Close();  
        }  
        finally  
        {  
            CloseConn();  
        }  
    }  
    #endregion  
#region 从数据库中读取图片,显示在当前页面
    /// <summary>
    /// 从数据库中读取图片,显示在当前页面(显示方式:step by step)
    /// </summary>
    /// <param name="ProcName">sql语句,查询字段为数据库中图片字段</param>
    /// <param name="prams">参数</param>
    /// <param name="Size">一次显示的字节数</param>
    /// <param name="p">需要显示图片的页面,只能为this.page</param>
    public static void GetImage(string ProcName, SqlParameter[] prams,int Size,Page p)
    {
        try
        {
            SqlCommand cmd = CreateCommand(ProcName, prams, CommandType.Text);
            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
            byte[] bytes = null;
            if (dr.Read())
            {
                int bufferSize = Size; //size of buffer.
                bytes = new byte[bufferSize]; //the buffer of data.
                long bytesRead; //the number of bytes read.
                long readForm = 0; //the starting index.

                //read the filed 100 bytes at a time.
                do
                {
                    bytesRead = dr.GetBytes(0, readForm, bytes, 0, bufferSize);
                    p.Response.BinaryWrite(bytes);
                    readForm += bufferSize;
                } while (bytesRead == bufferSize);
            }
            dr.Close();
        }
        finally
        {
            CloseConn();
        }
    }
    #endregion 

这个函数主要将图片分布显示出来,每次读取Size大小,直到没有数据可以读取(显示完毕)为止。其中page p指的是要显示图片的页面,呵呵,这也是这个方法的缺点所在:p必须为调用这个函数的页面,也就是this;同时这个页面只能显示这一个图片,呵呵,是不是很郁闷,下面介绍第二种方法。

<2>图文混排

首先在解决方案下新建一个.ashx文件(imageFromDb.ashx),在文件内删除部分代码,只保留以下代码[c-sharp] view plaincopyprint?<%@ WebHandler Language="C#" Class="imageFromDb" %>  
<%@ WebHandler Language="C#" Class="imageFromDb" %> 

新建一个类,名为imageFromDb.cs,写如一下代码

[c-sharp] view plaincopyprint?using System;  
using System.Web;  
using System.Data;  
using System.Data.SqlClient;  
  
public class imageFromDb : IHttpHandler  
{  
  
    public void ProcessRequest(HttpContext context)  
    {  
        string id = context.Request.QueryString["id"];  
        string type = context.Request.QueryString["type"];  
        string sql = null;  
        if (id == null) throw new ApplicationException("must specify ID");  
        if (type == null) throw new ApplicationException("must specify type");  
        SqlConnection conn = DBForSQL.CreateConn();  
        if (type == "class")  
        {  
            sql = "select classImage from tb_class where classID=@ID";  
        }  
        else if(type=="goods")  
        {  
            sql = "select goodsImage from tb_goods where goodsID=@ID";  
        }  
        if (sql != null)  
        {  
            SqlCommand cmd = new SqlCommand(sql, conn);  
            cmd.Parameters.AddWithValue("@ID", id);  
  
            try  
            {  
                conn.Open();  
                SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);  
                if (dr.Read())  
                {  
                    int bufferSize = 100;  
                    byte[] bytes = new byte[bufferSize];  
                    long bytesRead;  
                    long readFrom = 0;  
                    do  
                    {  
                        bytesRead = dr.GetBytes(0, readFrom, bytes, 0, bufferSize);  
                        context.Response.BinaryWrite(bytes);  
                        readFrom += bufferSize;  
                    } while (bytesRead == bufferSize);  
                }  
                dr.Close();  
            }  
            finally  
            {  
                conn.Close();  
            }  
        }  
  
    }  
  
    public bool IsReusable  
    {  
        get  
        {  
            return true;  
        }  
    }  
  
}  
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class imageFromDb : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string id = context.Request.QueryString["id"];
        string type = context.Request.QueryString["type"];
        string sql = null;
        if (id == null) throw new ApplicationException("must specify ID");
        if (type == null) throw new ApplicationException("must specify type");
        SqlConnection conn = DBForSQL.CreateConn();
        if (type == "class")
        {
            sql = "select classImage from tb_class where classID=@ID";
        }
        else if(type=="goods")
        {
            sql = "select goodsImage from tb_goods where goodsID=@ID";
        }
        if (sql != null)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@ID", id);

            try
            {
                conn.Open();
                SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
                if (dr.Read())
                {
                    int bufferSize = 100;
                    byte[] bytes = new byte[bufferSize];
                    long bytesRead;
                    long readFrom = 0;
                    do
                    {
                        bytesRead = dr.GetBytes(0, readFrom, bytes, 0, bufferSize);
                        context.Response.BinaryWrite(bytes);
                        readFrom += bufferSize;
                    } while (bytesRead == bufferSize);
                }
                dr.Close();
            }
            finally
            {
                conn.Close();
            }
        }

    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

}
 

这个类中的部分细节(如查询语句)读者可以自己更改

最后要做的就是在html控件img中显示图片了,方法如下

<img alt="" src="imageFromDB.ashx?id=<%#goodsID %>&type=goods"  style="height: 196px; width: 209px" />

 

ok完成了,图片可以显示了,并且不会影响网页中其他内容,不过建议你使用<img>控件,这样会减少很多麻烦……


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: SSM是指Spring+SpringMVC+Mybatis的开发框架,下面以这个开发框架为基础介绍如何实现图片上传并保存到数据库。 首先,需要在SpringMVC中配置文件上传的解析器。在SpringMVC的配置文件中添加以下代码: ```xml <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="52428800"/> <!-- 设置最大上传大小为50MB --> </bean> ``` 然后,在前端页面中添加一个文件选择的表单项: ```html <form action="uploadImage" method="post" enctype="multipart/form-data"> <input type="file" name="image"/> <input type="submit" value="上传图片"/> </form> ``` 接下来,在SpringMVC的控制器中添加对应的请求处理方法: ```java @RequestMapping(value = "/uploadImage", method = RequestMethod.POST) public String uploadImage(@RequestParam("image") MultipartFile file, Model model) { if (!file.isEmpty()) { try { // 保存图片到服务器目录 String path = "/path/to/save/image"; // 指定保存的路径 String filename = file.getOriginalFilename(); File savedFile = new File(path, filename); file.transferTo(savedFile); // 将图片信息保存到数据库 ImageEntity imageEntity = new ImageEntity(); imageEntity.setFilename(filename); imageEntity.setPath(path); imageService.saveImage(imageEntity); // 返回成功信息 model.addAttribute("message", "图片上传成功"); } catch (IOException e) { // 返回错误信息 model.addAttribute("message", "图片上传失败"); } } else { // 返回错误信息 model.addAttribute("message", "图片不能为空"); } return "upload_result"; // 返回结果页面 } ``` 最后,在Mybatis的Mapper文件中编写相应的SQL语句,实现将图片信息保存到数据库中。 以上就是使用SSM实现图片上传并保存到数据库的简单示例。需要注意的是,保存图片的路径需要根据实际情况进行配置,并且要确保服务器目录有写入权限。 ### 回答2: 在SSM框架中上传图片并保存到数据库,需要进行以下步骤: 1. 在前端页面中使用HTML的表单元素,添加一个文件选择框(type="file")用于选择要上传的图片文件,并设置一个提交按钮(type="submit")来触发文件上传操作。 2. 在后端的Controller类中,使用@RequestParam注解获取前端页面提交的图片文件,并将其保存到服务器的临时文件夹中。 3. 创建一个Service类来处理上传的图片文件,并将其保存到数据库中。首先,需要定义一个Model类来映射数据库中的表结构,包括一个字段来存储图片的二进制数据。同时,在Model类中添加一个字段来保存图片的文件名。然后,在Service类中,通过读取临时文件夹中的图片文件,将其转换为字节数组,并保存到Model类中的二进制字段中,同时保存图片的文件名到Model类中的文件名字段中。 4. 调用DAO层的方法将保存了图片二进制数据和文件名的Model类对象插入到数据库中。 5. 完成保存操作后,可以选择将临时文件夹中的图片文件删除,以节省磁盘空间。 综上所述,通过以上步骤,在SSM框架中实现了图片上传并保存到数据库的功能。 ### 回答3: 实现使用SSM框架上传图片并保存到数据库的步骤如下: 1. 前端页面部分: 在HTML表单中添加一个文件上传的输入框,用于用户选择要上传的图片文件。设置form的enctype属性为"multipart/form-data",这样可以支持文件上传。 ```html <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="imageFile"> <input type="submit" value="上传"> </form> ``` 2. 控制器部分: 在后端的控制器中添加方法来处理图片上传的请求,并将上传的图片存到数据库中。 ```java @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadImage(@RequestParam("imageFile") MultipartFile imageFile) { // 判断文件不为空且为图片 if (!imageFile.isEmpty() && imageFile.getContentType().startsWith("image")) { try { // 将图片文件保存到数据库中 byte[] imageBytes = imageFile.getBytes(); // 进行数据库保存操作,具体操作根据自己的数据库配置来实现 // ... return "上传成功"; } catch (IOException e) { e.printStackTrace(); } } return "上传失败"; } ``` 3. 配置文件部分: 在Spring的配置文件中添加MultipartResolver bean来支持文件上传。 ```xml <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="2097152"/> <!-- 设置文件上传大小限制,单位为字节 --> </bean> ``` 以上是使用SSM框架实现上传图片并保存到数据库的简单示例,具体代码实现需根据自己的业务需求进行更改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值