数据库中图片存储及读取

数据|数据库

开发环境:Window 2000、SQLServer2000、.Net Framework SDK正式版
开发语言:C#、ASP.Net
简介:数据库中图片存储及读取

说明:在ASP中,我们用Request.TotalBytes、Request.BinaryRead()来上传图片,这个可恶的BinaryRead()方法非常笨,单个文件上传倒没什么大事,单如果多个图片上专可就花大气力了…!而现在ASP.Net中将会把解决以前ASP中文件上传的种种问题,使你在ASP.Net中轻轻松松开发出功能强大的上传程序,下面大家看看例子啦。

首先在SQL Server中建立一个图片存储的数库表,SqlScript如下:

if exists (select * from dbo.sysobjects where id = object_id(N"[dbo].[image]") and OBJECTPROPERTY(id, N"IsUserTable") = 1)
drop table [dbo].[image]
GO

CREATE TABLE [dbo].[image] (
[img_pk] [int] IDENTITY (1, 1) NOT NULL ,
[img_name] [varchar] (50) NULL ,
[img_data] [image] NULL ,
[img_contenttype] [varchar] (50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[image] WITH NOCHECK ADD
CONSTRAINT [PK_image] PRIMARY KEY  NONCLUSTERED
(
  [img_pk]
)  ON [PRIMARY]
GO
------------------------------------------------------------
一、上传图片:
imgupload.aspx文件:
<%@ Page language="c#" Codebehind="imgupload.aspx.cs" AutoEventWireup="false" Inherits="study.uploadimage.imgupload" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
  <title>imgupload</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
  <form enctype="multipart/form-data" runat="server" id="form1" name="form1">
   文件名 <input type="text" id="imgName" runat="server" NAME="imgName">
   <br>
   选择文件 <input id="UploadFile" type="file" runat="server" NAME="UploadFile">
   <br>
   <asp:button Text="上传" runat="server" ID="Button1" />
  </form>
  <a href="imgview.aspx?id=1" target="_blank">看图</a>
</body>
</HTML>

codebehind文件:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;

namespace study.uploadimage
{
/// <summary>
/// imgupload 的摘要说明。
/// </summary>
public class imgupload : System.Web.UI.Page
{
  protected System.Web.UI.WebControls.Button Button1;
  protected System.Web.UI.HtmlControls.HtmlInputText imgName;
  protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;

  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
  }

  private void Button1_Click(object sender, System.EventArgs e)
  {
   Stream imgStream;
   int imgLen;
   string imgName_value;
   string imgContentType;
   string imgUploadedName;
   
   imgStream  = UploadFile.PostedFile.InputStream;
   imgLen =  UploadFile.PostedFile.ContentLength;
   imgUploadedName = UploadFile.PostedFile.FileName;
   byte[] imgBinaryData=new byte[imgLen];
   imgContentType = UploadFile.PostedFile.ContentType;
   imgName_value = imgName.Value;

   try
   {
    if(imgName_value.Length < 1)
    {
     imgName_value = GetLastRightOf("\\",imgUploadedName );
    }
   }
   catch(Exception myEx)
   {
    Response.Write(myEx.Message);
   }

   int n = imgStream.Read(imgBinaryData, 0, imgLen);          
   int NumRowsAffected = MyDatabaseMethod(imgName_value, imgBinaryData, imgContentType);
            if(NumRowsAffected > 0)
             Response.Write( "<BR> uploaded image " );
   else
             Response.Write ( "<BR> an error occurred uploading the image.d " );
  }
  public string GetLastRightOf(string LookFor,string myString)
  {
   int StrPos;
   StrPos = myString.LastIndexOf(LookFor);
   return myString.Substring(StrPos + 1);
  }
  public int MyDatabaseMethod(string imgName,byte[] imgbin,string imgcontenttype)
  {
   SqlConnection connection = new SqlConnection(Application["Test_Conn"].ToString());
   string SQL="INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( @img_name, @img_data,@img_contenttype )";
   SqlCommand command=new SqlCommand ( SQL,connection );
            
   SqlParameter param0=new SqlParameter ( "@img_name", SqlDbType.VarChar,50 );
   param0.Value = imgName;   
   command.Parameters.Add( param0 );            

   SqlParameter param1=new SqlParameter ( "@img_data", SqlDbType.Image );   
   param1.Value = imgbin;
   command.Parameters.Add( param1 );
            
   SqlParameter param2 =new SqlParameter ( "@img_contenttype", SqlDbType.VarChar,50 );
   param2.Value = imgcontenttype;
   command.Parameters.Add( param2 );
   
   connection.Open();
   int numRowsAffected = command.ExecuteNonQuery();
   connection.Close();
   return numRowsAffected;
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {    
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  
}
}

------------------------------------------------------------

二、浏览图片:
imgvies.aspx文件:
<%@ Page language="c#" Codebehind="imgview.aspx.cs" AutoEventWireup="false" Inherits="study.uploadimage.imgview" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
  <title>imgview</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
</body>
</HTML>

codebehind文件:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace study.uploadimage
{
/// <summary>
/// imgview 的摘要说明。
/// </summary>
public class imgview : System.Web.UI.Page
{

  private void Page_Load(object sender, System.EventArgs e)
  {
   SqlConnection myDSN = new SqlConnection(Application["Test_Conn"].ToString());
   myDSN.Open();

   int imgid = int.Parse(Request.QueryString["id"]);
   string sqlText = "SELECT img_name, img_data, img_contenttype FROM image where img_pk=" + imgid;
   Trace.Write(sqlText);
   SqlCommand MyCommand = new SqlCommand (sqlText, myDSN);
   SqlDataReader dr =MyCommand.ExecuteReader();
   if(dr.Read())
   {
    Response.ContentType = (dr["img_contenttype"].ToString());
    Response.BinaryWrite((byte[])dr["img_data"]);
   }   
   myDSN.Close();
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {    
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion
}
}

这样这个程序就完成了,简单吧。当然还很多改进之处,希望大家多想想多编编一定可以写出更多的图象上传程序。

时间: 2024-08-19 22:50:45

数据库中图片存储及读取的相关文章

php将数据库中的电话号码读取出来并生成图片_php实例

以下是代码: 复制代码 代码如下: <?php //前面不要有空行 $id=$_GET[id]; include("admin/config.php"); $sql="select * from user where id=$id"; $data=mysql_fetch_array(mysql_query($sql)); $p=SBC_DBC($data[Phone],1); function get_str($str,$strlen=16) { $str=s

使用链接服务器在异构数据库中查询数据

SQL Server提供了链接服务器用于分布式查询异构数据库.通过链接服务器可以链接到Oracle.Sybase.DB2.SQL Server等大型关系数据库,也可以连接到Access.Excel等文件数据库,甚至可以连接到目录服务(AD).索引服务等.要链接到一种数据库需要使用相应的接口.微软为很多数据库提供了驱动接口,所以可以直接使用,但是对于没有提供驱动的数据库比如Sybase,则需要在服务器上安装对应数据库厂商提供的驱动. 使用SSMS或者使用T-SQL语句配置成功链接服务器后便可通过:

winform中向数据库中读取图片

问题描述 以下是原代码://读取图片Byte[]mybyte=newByte[];mybyte=(byte[])read["pht_photo"];MemoryStreamms=newMemoryStream(mybyte);Imageimg=Image.FromStream(ms);picBox.Image=img;ms.Close();以下是出错信息未处理的"System.ArgumentException"类型其他信息:使用了无效参数(Parameterisn

C#将文件保存到数据库中或者从数据库中读取文件

在编程中我们常常会遇到"将文件保存到数据库中"这样一个问题,虽然这已不是什么高难度的问题,但对于一些刚刚开始编程的朋友来说可能是有一点困难.其实,方法非常的简单,只是可能由于这些朋友刚刚开始编程不久,一时没有找到方法而已. 下面介绍一下使用C#来完成此项任务. 首先,介绍一下保存文件到数据库中. 将文件保存到数据库中,实际上是将文件转换成二进制流后,将二进制流保存到数据库相应的字段中.在SQL Server中该字段的数据类型是Image,在Access中该字段的数据类型是OLE对象.

求助,数据库中读取数据生成张表

问题描述 小弟刚刚实习一个月,最近遇到个问题一直没有进展问题描述,从Mysql数据库中读取一个表,生成一个Excel表格,但是表格和表的结构不一样我怎么样写一个Servlet,来实现这个功能呢?我想知道的是生成这个表格,并把数据传入进去的步骤如果能有一种上传一个干净没有数据的Excel表格做模版向其中添加数据也是再好不过啦.拜托各位大神指点迷津了,您的一句指点将使我少走许多弯路,谢谢啦 解决方案 解决方案二:poi或者jxl都可以实现读数据库获取数据想必应该难不倒你最主要的是使用poi或者jxl

java读取excel2013版的内容并把读取出来的内容插入到数据库中

问题描述 java读取excel2013版的内容并把读取出来的内容插入到数据库中 想用java代码读取excel(2013)表格里的内容,但是excel里面有好几个sheet,还有好几个表,该怎么办,而且还要把读取出来的内容储存到数据库中去,求大神帮助 解决方案 public static List<String[]> readExcel(String filePath) { try { List<String[]> list = new ArrayList<String[]

contacts-如何从数据库中读取联系人信息?

问题描述 如何从数据库中读取联系人信息? 我想读取所有的联系人信息到 PhoneBookBean 中.PhoneBookBean 包含first_name lastname email_address,但是看起来很难读取 People.URL.使用 ContactsContract,需要 mime_type,并且必须提供 lookupKey,我需要迭代所有的联系人一个一个人输入.如何从数据库中读取联系人信息? 解决方案 解决方案: Intent intent = new Intent(Inten

asp.net关于根据gridview中取到的值从数据库中读取image类型的图片信息并显示

问题描述 asp.net关于根据gridview中取到的值从数据库中读取image类型的图片信息并显示 前台代码 <asp:GridView ID=""GridView1"" runat=""server"" AutoGenerateColumns=""False"" GridLines=""Vertical"" OnRowCommand=&

二进制数据-java从数据库中读取二进制文件并....

问题描述 java从数据库中读取二进制文件并.... java从postgresql数据库中读取bytea二进制并且生成文件(如word,pdf文件等)!在jsp页面上显示附件(如邮件形式那样的附件)并且可以下载!请问怎么实现啊?求解!谢谢了! 解决方案 首先你需要确定附件的类型及名称.然后下载很简单的,根据下载的请求返回 response.addHeader ("content-type", "application/RFC822"); response.addH