惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threat Research - Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
V
Vulnerabilities – Threatpost
GbyAI
GbyAI
P
Proofpoint News Feed
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
A
About on SuperTechFans
T
Tenable Blog
M
MIT News - Artificial intelligence
IT之家
IT之家
I
Intezer
D
DataBreaches.Net
爱范儿
爱范儿
T
Threatpost
C
CERT Recently Published Vulnerability Notes
云风的 BLOG
云风的 BLOG
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
K
Kaspersky official blog
大猫的无限游戏
大猫的无限游戏
A
Arctic Wolf
Y
Y Combinator Blog
Cyberwarzone
Cyberwarzone
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Darknet – Hacking Tools, Hacker News & Cyber Security
H
Help Net Security
Microsoft Security Blog
Microsoft Security Blog
Spread Privacy
Spread Privacy
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
AWS News Blog
AWS News Blog
博客园 - 聂微东
C
Check Point Blog
S
Securelist
有赞技术团队
有赞技术团队
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
Last Week in AI
Last Week in AI
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
D
Docker
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tailwind CSS Blog
L
Lohrmann on Cybersecurity
G
Google Developers Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LangChain Blog

博客园 - EA_Games

ASP.NET常用代码 - EA_Games - 博客园 Oracle中的OMS的代理服务启动不了的问题 .Net术语大全 DataGrid中的数据导入到Word和Excel_C# NHibernate 进阶 用Nhibernate怎么实现数据的添加、删除、修改简单程序 每个开发人员现在应该下载的十种必备工具 nhibernate入门系列: one-to-one映射 nhibernate入门系列: one-to-many映射 NHibernate快速指南 nhibernate入门系列: 对象持久化操作 ASP.NET 安全认证(三) -- 一点补充(或者叫优化) ASP.NET 安全认证(一) ASP.NET 安全认证(二) Winform如何存入、读取SQL SERVER数据库图片 无法运行ASP.NET Web应用程序 选择VB.Net还是C# ASP.NET中在线用户统计 在asp.net中访问sql server - EA_Games - 博客园
ASP.NET数据库中图片存储及读取
EA_Games · 2005-10-22 · via 博客园 - EA_Games

开发环境: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" %><%@ 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
{
 /// 


 /// imgupload 的摘要说明。
 /// 

 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( "
 uploaded image " );
   else
             response.write ( "
 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);
  }
  
  /// 


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

  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" %>
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
 }
}

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