打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
(5)用Oracle数据库存储图片文件

在前面的博文中,博主介绍了使用Access数据库来存储图片http://blog.sina.com.cn/s/blog_62cd5a980100vjpt.html,但是Oracle数据库毕竟和Access数据库存在差异,本文主要介绍使用Oracle数据库来存储图片文件,从实现过程来看。Oracle数据库和Access数据库在存储图片文件时还是不一样的

首先,在Oracle数据库中敬爱那个里一个存储图片的表

-- Create table
create table IMAGETABLE
(
 NUM       NUMBER not null,
  FILENAME  NVARCHAR2(30),
  FILETYPE  NVARCHAR2(20),
  FILELENGTH NUMBER,
  LOADDATE  NVARCHAR2(30),
 CONTENT   BLOB
)
tablespace LCERP_DATA
  pctfree 10
  pctused 40
  initrans 1
  maxtrans 255
  storage
  (
    initial64
    minextents1
    maxextentsunlimited
  );
-- Create/Recreate primary, unique and foreign keyconstraints
alter table IMAGETABLE
  add constraint NUM primary key (NUM)
  using index
  tablespace LCERP_DATA
  pctfree 10
  initrans 2
  maxtrans 255
  storage
  (
    initial64K
    minextents1
    maxextentsunlimited
  );
表中的NUM字段为自动增长型,不需要在程序中控制,自动增长的办法见博文http://blog.sina.com.cn/s/blog_62cd5a980100w6m5.html

后台程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client;
using System.Data;
using System.IO;
using System.Globalization;
public partial class InsertImageToOracle : System.Web.UI.Page
{
    protectedvoid Page_Load(object sender, EventArgs e)
    {
       if (!IsPostBack)
       {
           OracleConnection conn = getConnection();
           getData(conn);
           closeConnection(conn);
       }
       else
       {
           OracleConnection conn = getConnection();
           getData(conn);
           closeConnection(conn);
       }
    }
    publicOracleConnection getConnection()
    {
       OracleConnection conn = null;
       try
       {
           string connstr = "data source=orcl;userid=jde;password=jde;";
           conn = new OracleConnection(connstr);
           conn.Open();
       }
       catch (Exception e)
       {
           
           ScriptManager.RegisterStartupScript(this,this.GetType(),"","alert('建立数据库连接失败!');",true);
       }
       return conn;
    }
    public voidcloseConnection(OracleConnection conn)
    {
       try
       {
           conn.Close();
       }
       catch (Exception e)
       {
           
           ScriptManager.RegisterStartupScript(this,this.GetType(),"","alert('关闭数据库失败!');",true);
       }
    }
    public voidgetData(OracleConnection conn)
    {
       DataSet ds = new DataSet();
       try
       {
           string sql = "select * from IMAGETABLE";
           OracleDataAdapter oda = new OracleDataAdapter(sql,conn);
           oda.Fill(ds);
           ASPxGridView1.Caption = "<font color='red'size=+2>数据库中图片信息</font>";
           ASPxGridView1.DataSource = ds;
           ASPxGridView1.DataBind();
       }
       catch (Exception e)
       {
           
           ScriptManager.RegisterStartupScript(this,this.GetType(),"","alert('GridView获取数据源失败');",true);
       }
    }
    public voidDoImageToDataBase(object sender,EventArgs e)
    {
       if (this.FileUpload1.HasFile)
       {
           FileInfo fi = newFileInfo(this.FileUpload1.PostedFile.FileName);
           string filepath = fi.FullName;
           string filename = fi.Name;
           string filetype =filename.Substring(filename.IndexOf("."),filename.Length-filename.IndexOf("."));
           DateTime dt = System.DateTime.Now;
           string loadtime = dt.ToString("yyyy-MM-dd HH:m:ss");
           string time = dt.ToString("yyyyMMdd",DateTimeFormatInfo.InvariantInfo);
           filename = time + filetype;
           long filelength = fi.Length;
           FileStream fs = newFileStream(filepath,FileMode.Open,FileAccess.Read);
           BinaryReader br = new BinaryReader(fs);
           byte[] myByte = new byte[fs.Length];
           br.Read(myByte,0,Convert.ToInt32(myByte.Length));
           fs.Close();
           OracleConnection conn = getConnection();
           OracleCommand command = conn.CreateCommand();
           command.CommandText = @"insert intoImageTable(filename,filetype,loaddate,filelength) values('" +filename + "','" + filetype + "','" + loadtime + "'," + filelength+")";
           command.CommandType = CommandType.Text;
           OracleCommand com = conn.CreateCommand();
           com.CommandText = "update imagetableset content=:photo where filename='" + filename +"'";
           OracleParameter photo = new OracleParameter("photo",OracleDbType.Blob);
           photo.Value = myByte;
           com.Parameters.Add(photo);
           try
           {
               command.ExecuteNonQuery();
               com.ExecuteNonQuery();
               ScriptManager.RegisterStartupScript(this,this.GetType(),"","alert('插入图片成功!');",true);
           }
           catch (Exception ee)
           {
               ScriptManager.RegisterStartupScript(this, this.GetType(), "","alert('插入图片失败!');", true);
               Response.Write(ee.StackTrace);
               
           }
           closeConnection(conn);
       }
       else
       {
           ScriptManager.RegisterStartupScript(this,this.GetType(),"","alert('请先选择文件!');",true);
       }
    }
    public voidshowPicture(object sender, EventArgs e)
    {
       LinkButton lk = (LinkButton)sender;
       int num = int.Parse(lk.CommandArgument.ToString());
       string sql = "select content from imagetable wherenum="+num+"";
       OracleConnection conn = getConnection();
       DataSet ds = new DataSet();
       OracleDataAdapter oda = new OracleDataAdapter(sql,conn);
       oda.Fill(ds);
       byte []img=new byte[0];
       if (ds != null)
       {
           DataRow dr = ds.Tables[0].Rows[0];
           if (!dr["content"].ToString().Equals(""))
           {
               img = (byte[])dr["content"];
               Response.ContentType = "image/jpeg";
               Response.BinaryWrite(img);
           }
           else
           {
               ScriptManager.RegisterStartupScript(this, this.GetType(), "","alert('请求的图片不存在');", true);
           }
       }
       closeConnection(conn);
    }
}
前台代码:

<%@ Page Language="C#" CodeFile="InsertImageToOracle.aspx.cs"Inherits="InsertImageToOracle" %>

<%@ RegisterAssembly="DevExpress.Web.ASPxGridView.v9.2, Version=9.2.2.0,Culture=neutral, PublicKeyToken=b88d1754d700e49a"
   Namespace="DevExpress.Web.ASPxGridView" TagPrefix="dxwgv"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>将图片存入Oracle数据库</title>
</head>
<body>
   <form id="form1"runat="server">
   <div align="center">
    <asp:Table ID="table1"runat="server">
    <asp:TableRow>
    <asp:TableCell>请选择图片</asp:TableCell>
    <asp:TableCell>
        <asp:FileUpload ID="FileUpload1" runat="server"/></asp:TableCell>
    </asp:TableRow>
    <asp:TableRow>
    <asp:TableCellColumnSpan="2"><asp:ButtonID="button1" runat="server" OnClick="DoImageToDataBase"Text="提交"/></asp:TableCell>
    </asp:TableRow>
    </asp:Table>
    
   <dxwgv:ASPxGridView ID="ASPxGridView1"runat="server"
           CssFilePath="~/App_Themes/Office2003Blue/{0}/styles.css"
           CssPostfix="Office2003_Blue"KeyFieldName="NUM">
       <StylesCssFilePath="~/App_Themes/Office2003Blue/{0}/styles.css"
           CssPostfix="Office2003_Blue">
           <Header ImageSpacing="5px"SortingImageSpacing="5px">
           </Header>
           <LoadingPanelImageSpacing="10px">
           </LoadingPanel>
       </Styles>
       <ImagesImageFolder="~/App_Themes/Office2003Blue/{0}/">
           <CollapsedButton Height="12px"
               Url="~/App_Themes/Office2003Blue/GridView/gvCollapsedButton.png"Width="11px" />
           <ExpandedButton Height="12px"
               Url="~/App_Themes/Office2003Blue/GridView/gvExpandedButton.png"Width="11px" />
           <DetailCollapsedButton Height="12px"
               Url="~/App_Themes/Office2003Blue/GridView/gvCollapsedButton.png"Width="11px" />
           <DetailExpandedButton Height="12px"
               Url="~/App_Themes/Office2003Blue/GridView/gvExpandedButton.png"Width="11px" />
           <FilterRowButton Height="13px" Width="13px"/>
       </Images>
       <StylesEditors>
           <ProgressBar Height="25px">
           </ProgressBar>
       </StylesEditors>
       <Columns>
       <dxwgv:GridViewDataTextColumn FieldName="NUM"Caption="序号"Width="50px"></dxwgv:GridViewDataTextColumn>
         <dxwgv:GridViewDataTextColumn FieldName="FILENAME"Caption="文件名"Width="100px"></dxwgv:GridViewDataTextColumn>
         <dxwgv:GridViewDataTextColumn FieldName="FILETYPE"Caption="文件类型"Width="80px"></dxwgv:GridViewDataTextColumn>
         <dxwgv:GridViewDataTextColumn FieldName="FILELENGTH"Caption="文件大小(B)"Width="150px"></dxwgv:GridViewDataTextColumn>
         <dxwgv:GridViewDataTextColumn FieldName="LOADDATE"Caption="上传日期"Width="150px"></dxwgv:GridViewDataTextColumn>
         <dxwgv:GridViewDataTextColumn>
         <DataItemTemplate>
         <asp:LinkButton ID="button"CommandArgument='<%#eval_r("NUM") %>'OnClick="showPicture" runat="server"Text="点击查看"/>
         </DataItemTemplate>
         </dxwgv:GridViewDataTextColumn>
       </Columns>
   </dxwgv:ASPxGridView>
   </div>
   
   </form>
</body>
</html>
红色的部分是本文要阐述的重点,access数据库存储你图片的博文中是直接将二进制流插入到数据库中对应的字段的,但是Oracle的Blob大字段的处理方法要稍微有一点不同首先需要对其给一个空值然后再进行更新,希望大家可以和博文http://blog.sina.com.cn/s/blog_62cd5a980100vjpt.html对比着看。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
asp.net 后台弹出提示框
NET使用了UpdatePanel后如何弹出对话框!
在ASP.NET页面上添加AJAX控件后,不能调出窗口的解决办法:
使用javascript动态调用样式表代码
ScriptManager.RegisterStartupScript方法
把Excel数据导入数据库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服