zoukankan      html  css  js  c++  java
  • SQLserver中存储图片

    两种方式
    1、存放图片路径
    2、转换成2进制流(不过这样的话将很占用数据库空间)
    存路径的方式就很简单了,下面着重给出转换成2进制流的存入以及读取方法。
    存入:
    string FilePath="";
    OpenFileDialog oFileDialog=new OpenFileDialog();
    if(oFileDialog.ShowDialog()==DialogResult.OK)
    {
    FilePath=oFileDialog.FileName;
    FileStream fs=new FileStream(FilePath,FileMode.Open,FileAccess.Read);
    byte[] bytes=new byte[fs.Length];
    string sql = "insert PicSave(FileName,FileType,FileData)values(@FN,@FT,@MF)";
    SqlCommand com = new SqlCommand(sql,this.sqlCon);
    SqlParameter FN = new SqlParameter("@FN",SqlDbType.VarChar);
    FN.Value = "泳装妹妹";
    com.Parameters.Add(FN);
    SqlParameter FT = new SqlParameter("@FT",SqlDbType.VarChar);
    FT.Value = "JPG";
    com.Parameters.Add(FT);
    SqlParameter MF = new SqlParameter("@MF",SqlDbType.Image);
    MF.Value = bytes;
    com.Parameters.Add(MF);
    com.CommandType = CommandType.Text;

    sqlCon.ConnectionString = this.conStr;

    try
    {
    sqlCon.Open();
    com.ExecuteNonQuery();
    sqlCon.Close();
    MessageBox.Show("存入成功!");
    }
    catch(Exception ex)
    {
    throw ex;
    }
    finally
    {
    sqlCon.Close();
    }

    }
    读出:
    int id=Convert.ToInt32(this.textBox1.Text.Trim());
    string sql = "select FileData from PicSave where id ="+id+" ";

    sqlCon.ConnectionString = this.conStr;

    SqlCommand readComm = new SqlCommand(sql,this.sqlCon);

    SqlDataReader dr = null;

    FileStream fs = null;

    BinaryWriter bw = null;

    int bufferSize = 100;

    byte[] outbyte = new byte[bufferSize];

    long retval;

    long startIndex = 0;

    try
    {
    sqlCon.Open();
    dr = readComm.ExecuteReader();
    while(dr.Read())
    {
    fs = new FileStream("TakeOut.jpg",FileMode.OpenOrCreate,FileAccess.Write);

    bw = new BinaryWriter(fs);

    retval = dr.GetBytes(0, startIndex, outbyte, 0, bufferSize);

    while (retval == bufferSize)
    {
    bw.Write(outbyte);
    bw.Flush();

    startIndex += bufferSize;
    retval = dr.GetBytes(0, startIndex, outbyte, 0, bufferSize);
    }
    bw.Write(outbyte, 0, (int)retval - 1);
    bw.Flush();
    bw.Close();
    fs.Close();
    Image im = Image.FromFile("TakeOut.jpg");

    this.pictureBox1.Image = im;
    }
    sqlCon.Close();
    }
    catch(Exception ex)
    {
    throw ex;
    }
    finally
    {
    sqlCon.Close();
    bw.Close();
    fs.Close();
    }

  • 相关阅读:
    httpmime-session 会话保持
    5.5 准备创建bean
    5.4 获取单例
    当有“Button1.Attributes.Add("onclick", "return confirm('你确定要保存修改吗?')");”时,验证控件失效的解决方法
    asp.net刷新本页面的六种方法总结
    return 、break和continue的区别和作用
    OnClientClick事件
    抽象接口
    C# 中的EventHandler实例详解-转
    GridView点击行触发SelectedIndexChanged事件
  • 原文地址:https://www.cnblogs.com/ZGQ-VIP/p/11800413.html
Copyright © 2011-2022 走看看