日期:2012-06-13  浏览次数:20386 次

开发环境: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;