显示:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;namespace myUpLoad
{
/// <summary>
/// showimg 的摘要说明。
/// </summary>
public class showimg : System.Web.UI.Page
{
protected SqlConnection myConnection;private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
string imgID=Request.QueryString["imgid"];
string conn="server=(local);database=test;uid=sa;pwd=ilovenm";
//string conn="server=(local);database=test;uid=sa;pwd=ilovenm";
            myConnection=new SqlConnection(conn);string selectCmd="select imgdata,imgtype from image where id="+imgID;
SqlCommand myCommand=new SqlCommand(selectCmd,myConnection);
myConnection.Open();
SqlDataReader myDataReader=myCommand.ExecuteReader();if (myDataReader.Read())
{
Response.ContentType=myDataReader["imgtype"].ToString();
Response.BinaryWrite((byte[])myDataReader["imgdata"]);
}
}#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
}
}

解决方案 »

  1.   

    你可以用一个aspx页,专门用来显示图片,只要传递一个ID进去就OK了
    在主页中这个显示<image url="show.aspx?id=212">
      

  2.   

    1. 文章标题:asp.net上传图片并同时生成缩略图 
      
    <script language="VB" runat="server">
    Sub UploadFile(sender As Object, e As EventArgs)If FileUp.PostedFile.ContentLength = 0 Then
    FileInfo.Visible = False
    Exit Sub
    Else
    FileInfo.Visible = True
    FDisplay1.Visible = True
    End IfFSize.Text ="上传文件大小"+ CStr(FileUp.PostedFile.ContentLength/1024)+"KB"
    FName.Text = "已上传文件名:"+FileUp.PostedFile.FileName+"<br>"+FName.Text'写入数据库
    on error resume next
    dim myconn as sqlconnection
    dim mycomm as sqlcommand
    dim sql as string
    dim id as integer
    Dim image,anewimage As System.Drawing.Image
    dim width,height,newwidth,newheight as integer
    Dim callb As System.Drawing.Image.GetThumbnailImageAbort
    myConn=New sqlconnection(ConfigurationSettings.AppSettings("数据库"))
    myconn.open()
    sql="insert into picture (姓名,班级,介绍,属性) values ('"&request.cookies("dgxyl").values("dgxylname")&"','"&request.cookies("dgxyl").values("dgxylbj")&"','"&trim(request("TextBox1"))&"','"&request("r1")&"')"
    Mycomm=New sqlcommand(sql,myconn)
    mycomm.executenonquery()
    myconn.close()Dim myCommand As New SqlCommand("select top 1 id from picture order by id desc", myConn)
    myCommand.Connection.Open()
    Dim myReader As SqlDataReader=mycommand.executereader()
    if myReader.Read() then
    id=myReader("id")
    end if
    myconn.close()
    '保存图片
    FileUp.PostedFile.SaveAs( Server.MapPath("\classpic\")&cstr(id)&".jpg" )
    '生成缩略图
    image=System.Drawing.Image.FromFile(Server.MapPath("/classpic/"+cstr(id)+".jpg"))
    width=image.Width
    height=image.height
    if width>height then
    newwidth=250
    newheight=image.height/image.Width*newwidth
    else
    newheight=250
    newwidth=image.Width/image.height*newheight
    end if
    response.write("id="+cstr(id)+"width="+cstr(Width)+";height="+cstr(height)+"  ")
    response.write("newwidth="+cstr(newwidth)+";newheight="+cstr(newheight)+"<br>")aNewImage=image.GetThumbnailImage(newwidth,newheight,callb,new System.IntPtr())
    aNewImage.Save(Server.MapPath("/smallpic/"+cstr(id)+".jpg"))
    image.Dispose()
    Dim FileSplit() As String = Split( FileUp.PostedFile.FileName, "\" )
    Dim FileName As String = FileSplit(FileSplit.Length-1)
    Dim Exts() As String = Split( FileName, "." )
    Dim Ext As String = LCase(Exts(Exts.Length-1))FDisplay.Text = "<A Target='_blank' HREF='/classpic/"&cstr(id)&".jpg"& "'>查看上传文件</A>"
    FDisplay1.text="<a href='/picture/default.asp?bj="&cstr(request.cookies("dgxyl").values("dgxylbj"))&"'>返回</a>"
    End Sub
      

  3.   

    在ASP.NET中存取图片到数据库的示例
    //开发环境:Window 2000、SQLServer2000、.Net Framework SDK正式版
         //开发语言:C#、ASP.Net
         //简介:数据库中图片存蓄及读取
             /*
         说明:在ASP中,我们用Request.TotalBytes、Request.BinaryRead()来上传图片,这个可恶的BinaryRead()方法非常笨,单个文件上传倒没什么大事,单如果多个图片上专可就花大气力了…!而现在ASP.Net中将会把解决以前ASP中文件上传的种种问题,使你在ASP.Net中轻轻松松开发出功能强大的上传程序,下面大家看看例子啦。
         */
              
         /*
         首先在SQL Server中建立一个图片存储的数库表,ImageData Column为图象二进制数据储存字段,ImageContentType Column为图象文件类型记录字段,ImageDescription Column为储蓄图象文件说明字段,ImageSize Column为储存图象文件长度字段,结构如下:
         CREATE TABLE [dbo].[ImageStore] (
         [ImageID] [int] IDENTITY (1, 1) NOT NULL ,
         [ImageData] [image] NULL , 
         [ImageContentType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
         [ImageDescription] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
         [ImageSize] [int] NULL 
         ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
         */ 
         
         //UpLoadImage.aspx程序内容如下:
         <%@ Page Inherits="UploadImage.UploadImage" SRC="UpLoadImage.cs" Language="C#"%>
         <HTML><title>上传图片</title>
         <BODY bgcolor="#FFFFFF">
         <FORM ENCTYPE="multipart/form-data" RUNAT="server" ID="Form1">
         <TABLE RUNAT="server" WIDTH="700" ALIGN="left" ID="Table1" cellpadding="0" cellspacing="0" border="0">
         <TR>
         <TD>上传图片(选择你要上传的图片)</TD>
         <TD>
         <INPUT TYPE="file" ID="UP_FILE" RUNAT="server" STYLE="Width:320" ACCEPT="text/*" NAME="UP_FILE">
         </TD>
         </TR>
         <TR>
         <TD> 
         文件说明(添加上传图片说明,如:作者、出处)
         </TD>
         <TD>
         <asp:TextBox RUNAT="server" WIDTH="239" ID="txtDescription" MAINTAINSTATE="false" />
         </TD>
         </TR>
         <TR>
         <TD>
         <asp:Label RUNAT="server" ID="txtMessage" FORECOLOR="red" MAINTAINSTATE="false" />
         </TD>
         <TD>
         <asp:Button RUNAT="server" WIDTH="239" onCLICK="Button_Submit" TEXT="Upload Image" />
         </TD>
         </TR>
         </TABLE>
         </FORM>
         </BODY>
         </HTML>
         //-------------------------------------------------------------------
         //UpLoadImage.cs程序内容如下:
         using System;
         using System.Web;
         using System.IO;
         using System.Data;
         using System.Data.SqlClient;
         using System.Web.UI;
         using System.Web.UI.WebControls;
         using System.Web.UI.HtmlControls; 
         namespace UploadImage
         { 
         public class UploadImage : Page { 
         protected HtmlInputFile UP_FILE; //HtmlControl、WebControls控件对象
         protected TextBox txtDescription;
         protected Label txtMessage;
         protected Int32 FileLength = 0; //记录文件长度变量 
         protected void Button_Submit(System.Object sender, System.EventArgs e) {
         HttpPostedFile UpFile = UP_FILE.PostedFile; //HttpPostedFile对象,用于读取图象文件属性
         FileLength = UpFile.ContentLength; //记录文件长度 
         try {
         if (FileLength == 0) { //文件长度为零时
         txtMessage.Text = "<b>请你选择你要上传的文件</b>"; 
         } else {
         Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
         Stream StreamObject = UpFile.InputStream; //建立数据流对像
         //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
         StreamObject.Read(FileByteArray,0,FileLength); 
         //建立SQL Server链接
         SqlConnection Con = new SqlConnection("Data Source=Localhost;Initial Catalog=testdb;User ID=sa;Pwd=;");
         String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) valueS (@Image, @ContentType, @ImageDescription, @ImageSize)";
         SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
         CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).value = FileByteArray;
         CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).value = UpFile.ContentType; //记录文件类型
         //把其它单表数据记录上传
         CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).value = txtDescription.Text;
         //记录文件长度,读取时使用
         CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).value = UpFile.ContentLength;
         Con.Open();
         CmdObj.ExecuteNonQuery(); 
         Con.Close();
         txtMessage.Text = "<p><b>OK!你已经成功上传你的图片</b>";//提示上传成功
         }
         } catch (Exception ex) {
         txtMessage.Text = ex.Message.ToString();
         }}}}
         //----------------------------------------------------------------------
         //好了,图片已经上传到数据库,现在还要干什么呢?当然是在数据库中读取及显示在Web页中啦,请看以下程序:
         //ReadImage.aspx程序内容如下:
         /----------------------------------------------------------------------- 
         <%@ Page Inherits="ReadImage.MainDisplay" SRC="ReadImage.cs"%> 
         //----------------------------------------------------------------------
         //ReadImage.cs程序内容如下:
         using System;
         using System.Data;
         using System.Data.SqlClient;
         using System.Web.UI;
         using System.Web.UI.WebControls;
         using System.Web.UI.HtmlControls;
         namespace ReadImage {
         public class MainDisplay : System.Web.UI.Page {
         public void Page_Load(System.Object sender, System.EventArgs e) {
         int ImgID = Convert.ToInt32(Request.QueryString["ImgID"]); //ImgID为图片ID 
         //建立数据库链接
         SqlConnection Con = new SqlConnection("Data Source=KING;Initial Catalog=testdb;User ID=sa;Pwd=;");
         String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
         SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
         CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).value = ImgID;
         Con.Open();
         SqlDataReader SqlReader = CmdObj.ExecuteReader();
         SqlReader.Read(); 
         Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型
         //输出图象文件二进制数制
         Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]); 
         Response.End();
         Con.Close();
         //很简单吧^_^
         }
         }
         }
         //--------------------------------------------------------------------
         //最后,我们当然要把它在Web页面显示出来啦
         //ShowImage.hml
         <html>
         <body>
         这个是从数据库读取出来的图象:<img src="ReadImage.aspx?ImgID=1">
         <body>
         </html>
      

  4.   

    1. 文章标题:asp.net上传图片并同时生成缩略图 
      
    <script language="VB" runat="server">
    Sub UploadFile(sender As Object, e As EventArgs)If FileUp.PostedFile.ContentLength = 0 Then
    FileInfo.Visible = False
    Exit Sub
    Else
    FileInfo.Visible = True
    FDisplay1.Visible = True
    End IfFSize.Text ="上传文件大小"+ CStr(FileUp.PostedFile.ContentLength/1024)+"KB"
    FName.Text = "已上传文件名:"+FileUp.PostedFile.FileName+"<br>"+FName.Text'写入数据库
    on error resume next
    dim myconn as sqlconnection
    dim mycomm as sqlcommand
    dim sql as string
    dim id as integer
    Dim image,anewimage As System.Drawing.Image
    dim width,height,newwidth,newheight as integer
    Dim callb As System.Drawing.Image.GetThumbnailImageAbort
    myConn=New sqlconnection(ConfigurationSettings.AppSettings("数据库"))
    myconn.open()
    sql="insert into picture (姓名,班级,介绍,属性) values ('"&request.cookies("dgxyl").values("dgxylname")&"','"&request.cookies("dgxyl").values("dgxylbj")&"','"&trim(request("TextBox1"))&"','"&request("r1")&"')"
    Mycomm=New sqlcommand(sql,myconn)
    mycomm.executenonquery()
    myconn.close()Dim myCommand As New SqlCommand("select top 1 id from picture order by id desc", myConn)
    myCommand.Connection.Open()
    Dim myReader As SqlDataReader=mycommand.executereader()
    if myReader.Read() then
    id=myReader("id")
    end if
    myconn.close()
    '保存图片
    FileUp.PostedFile.SaveAs( Server.MapPath("\classpic\")&cstr(id)&".jpg" )
    '生成缩略图
    image=System.Drawing.Image.FromFile(Server.MapPath("/classpic/"+cstr(id)+".jpg"))
    width=image.Width
    height=image.height
    if width>height then
    newwidth=250
    newheight=image.height/image.Width*newwidth
    else
    newheight=250
    newwidth=image.Width/image.height*newheight
    end if
    response.write("id="+cstr(id)+"width="+cstr(Width)+";height="+cstr(height)+"  ")
    response.write("newwidth="+cstr(newwidth)+";newheight="+cstr(newheight)+"<br>")aNewImage=image.GetThumbnailImage(newwidth,newheight,callb,new System.IntPtr())
    aNewImage.Save(Server.MapPath("/smallpic/"+cstr(id)+".jpg"))
    image.Dispose()
    Dim FileSplit() As String = Split( FileUp.PostedFile.FileName, "\" )
    Dim FileName As String = FileSplit(FileSplit.Length-1)
    Dim Exts() As String = Split( FileName, "." )
    Dim Ext As String = LCase(Exts(Exts.Length-1))FDisplay.Text = "<A Target='_blank' HREF='/classpic/"&cstr(id)&".jpg"& "'>查看上传文件</A>"
    FDisplay1.text="<a href='/picture/default.asp?bj="&cstr(request.cookies("dgxyl").values("dgxylbj"))&"'>返回</a>"
    End Sub
      

  5.   

    </script>
    <SCRIPT language=JavaScript>
    <!--
    var requestsubmitted=false;
    function guestbook_Validator(theForm)
    {
    //检查是否从新提交
    if (requestsubmitted==true){
      alert("你已经提交了留言,请等待服务器应答!");
      return(false);
     }
    requestsubmitted=true;return (true);
    }
    //-->
    </SCRIPT>
    <Html>
    <Body BgColor=White>
    <H3 align="center">请正确填写下面各项</h3>
    <Hr></H3>
    <Div id="FileInfo" Visible="False" runat="server">
     <Asp:Label id="FSize" runat="server"/><br>
     <Asp:Label id="FName" runat="server"/><br>
    <Asp:Label id="FDisplay" runat="server"/>
     <Asp:Label id="FDisplay1" runat="server"/>
    </Div>
    <Form Enctype="multipart/form-data" onsubmit="return guestbook_Validator(this)" runat="server">
    上传文件
    <Input Type="File" id="FileUp" runat="server" size="20"><br>
    图片属性:<input type="radio" value="<%=request.cookies("dgxyl").values("dgxylbj")%>" name="R1" checked>本班<input type="radio" value="全校" name="R1">全校(本班则只在本班显示,全校则在全校显示)<P>
    图片说明:<br>
    <asp:TextBox id="TextBox1" runat="server" Width="233px" Height="141px">
    </asp:TextBox>
            <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="请输入图片说明">
    </asp:RequiredFieldValidator><br>
    <Asp:button id="Upload" OnClick="UploadFile" Text="上传图片" runat="server"/>
    </form>
    <Hr>
    <p>注意:</p>
    <ol>
      <li><b>严禁上传污染环境的照片,否则账号将被删除!</b></li>
      <li><font color="#808000"><b>请详细填写照片说明,图片说明不详细将会被视为乱传图片,将会被删除!</b></font></li>
    </ol>
    <p> </p></Body>
    </Html>