热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

写入和读取图片(c#asp.netsqlserver)

作者:木子http:blog.csdn.netderny首先要创建一个表包含自段image和type类型各自为image和vnancharWebForm1.aspx<%@

作者:木子  http://blog.csdn.net/derny/

首先要创建一个表包含自段image 和 type 类型各自为image 和 vnanchar

WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="ReadAndWritePicFromDB.WebForm1" %>

 

WebForm1.aspx.cs

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 ReadAndWritePicFromDB
{
 ///


 /// WebForm1 的摘要说明。
 ///

 public class WebForm1 : System.Web.UI.Page
 {
  protected System.Web.UI.HtmlControls.HtmlInputFile File1;
  protected System.Web.UI.WebControls.Button Button1;
  private string fileName = "" ;
  protected System.Web.UI.WebControls.Button Button2;
  private static SqlConnection conn  = null;
  
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   ConnectDB();
  }

  //得到文件名
  private string GetFile()
  {
   HttpPostedFile file = File1.PostedFile;
   fileName = file.FileName;

   return fileName;
  }

  //读取文件内容
  private byte[] ReadFile()
  {
   FileStream file = File.OpenRead(GetFile());
   byte[] cOntent= new byte[file.Length];
   file.Read(content,0,content.Length);
   file.Close();
   
   return content;
  }

  //连接数据库
  private void ConnectDB()
  {
   string cOnnStr= "Initial Catalog=;Data Source=;User ID=;Password=;";
   cOnn= new SqlConnection(connStr);
   conn.Open();
  }

  //写入图片到数据库中
  private void WriteImage()
  {
   SqlCommand comm = conn.CreateCommand();
   comm.CommandText = "insert into images(image,type) values(@image,@type)";
   comm.CommandType = CommandType.Text;
   SqlParameter param = comm.Parameters.Add("@image",SqlDbType.Image);
   param.Value = ReadFile();
   param = comm.Parameters.Add("@type",SqlDbType.NVarChar);
   param.Value = GetContentType(new FileInfo(fileName).Extension.Remove(0,1));

   if(comm.ExecuteNonQuery() == 1)
    Response.Write("Successful");
   else
    Response.Write("Fail");
   
   conn.Close();
  }

  //获取图片的后缀名
  private string GetContentType(string extension)
  {
   string type = "";

   if(extension.Equals("jpg") || extension.Equals("JPG"))
    type = "jpeg";
   else
    type = extension;

   return "image/"+type;
  }

  //从数据库中读取图片
  private void ReadImage()
  {
   SqlCommand comm = conn.CreateCommand();
   comm.CommandText = "select image,type from images";
   comm.CommandType = CommandType.Text;

   SqlDataReader reader = comm.ExecuteReader();
   while(reader.Read())
   {
    Response.COntentType= reader["type"].ToString();//读写类型  一定要设置 否则浏览器会当作文本输出
    Response.BinaryWrite((byte[])reader["image"]);//图片数据
   }

   Response.Write("Successful");
   Response.End();

   conn.Close();
  }
  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  ///


  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///

  private void InitializeComponent()
  {   
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.Button2.Click += new System.EventHandler(this.Button2_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Button1_Click(object sender, System.EventArgs e)
  {
   WriteImage();
  }

  private void Button2_Click(object sender, System.EventArgs e)
  {
   try
   {
    ReadImage();
   }
   catch(Exception ep)
   {
    conn.Close();
    Response.End();
   }
  }
 }
}


推荐阅读
  • 转载:http:www.crazycoder.cnDataBaseIndex.html查询速度慢的原因很多,常见如下几种:1、没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设 ... [详细]
  • 缓存的重要性就不用再强调了,@OutputCache给我们提供了一种声明的方式(对应的还有编程的方式)来控制页面和用户控件的缓存策略,这是一种最简单直接的网站优化方式。还是先来过一遍@ ... [详细]
  • 只能输入数字的TextBox
    只能接受数字1usingSystem;2usingSystem.Text;3usingSystem.Web;4usingSystem.Web.UI;5usingSystem.Web ... [详细]
  • 第一部分:TSqlTop有两种用法1,限制查询结果集返回的行数或总行数的百分比。当将TOP与ORDERBY子句结合使用时,结果集限制为前N个已排序行;否则,以未定义的顺序返回前N个 ... [详细]
  • 媒介这里大部份是本身碰到过的状况,另有一部份自创了偕行的文章,假如人人有碰到别的坑,迎接提出来一同研讨。学问要点1.Meta标签1.制止用户缩放页面,页面强迫让文档的宽度与装备的宽 ... [详细]
  • dremio的学习点滴
    在连接数据源后,进行数据源反射的创建,dremio会在本地创建一个类似于副本的文件,具体目录未知,当下次去执行sql时,则会启动加速器进行查询速度的优化。反射策略:fullupda ... [详细]
  • Today,IstartedtocreateacoupleofJSPpagesfortheserver-sidepartofmyMScthesisprojectinordertob ... [详细]
  • DimcnAsNewADODB.ConnectionDimcmdAsNewADODB.CommandDimrstAsNewADODB.Recordsetcn.Mod ... [详细]
  • 本文讨论了如何使用Web.Config进行自定义配置节的配置转换。作者提到,他将msbuild设置为详细模式,但转换却忽略了带有替换转换的自定义部分的存在。 ... [详细]
  • 定制数据层关键字:数据层,访问,元数据,数据访问模型http://www.gaodaima.com/35448.html定制数据层_sqlserver ... [详细]
  • 在目标队列中对消息进行排队时出现异常。错误:15404,状态:19。CouldnotobtaininformationaboutWindowsNTgroupuserSERVER ... [详细]
  • SqlServer分区表概述(转载)
    什么是分区表一般情况下,我们建立数据库表时,表数据都存放在一个文件里。但是如果是分区表的话,表数据就会按照你指定的规则分放到不同的文件里,把一个大的数据文件拆分为多个小文件,还可以把这些小文件 ... [详细]
  • php5.3.x访问sqlserver2005
    由于项目需要,临时用php访问Sqlserver数据库,于是配置mssql扩展,但是无法访问,按照网上各种dll文件copy都不成功,最后终于发现是php版本问题,我的版本是php5.3 ... [详细]
  • C#设计模式(8)——桥接模式(Bridge Pattern)
    原文地址:http:www.cnblogs.comzhilipBridgePattern.html原文作者:Learninghard原文出处:博客园一、引言 ... [详细]
  • Spring Cloud笔记Spring Cloud Stream消息驱动(十五)
    1.消息驱动概述1.SpringCloudStream是什么SpringCloudStream是一个构建消息驱动微服务的框架。应用程序通过Inpust和Outputs与Spri ... [详细]
author-avatar
手机用户2502913853
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有