打印本文 打印本文 关闭窗口 关闭窗口
将图片插入数据库并使用asp.net读取出来的正确方法
作者:武汉SEO闵涛  文章来源:敏韬网  点击数4151  更新时间:2009/4/23 10:45:58  文章录入:mintao  责任编辑:mintao
 

                SqlCommand comm=conn.CreateCommand();

                comm.CommandText="select * from Images where id=@id";

                comm.CommandType=CommandType.Text;

 

                comm.Parameters.Add("@id", SqlDbType.BigInt).Value=int.Parse(Request["id"]);

 

                SqlDataReader reader=comm.ExecuteReader();

                while(reader.Read())

                {

                    Response.ContentType=reader["contentType"].ToString();

                    Response.BinaryWrite((byte[])reader["Image"]);

                }

                Response.End();

 

                conn.Close();

            }

            catch

            {

                Response.End();

            }

这段代码可置于Page_Load事件中,数据图片要注意的两点是:

一、              设置正确的ContentType(http中的content-type),图片的content-type格式一般为image/*,如jpeg为image/jpeg,bmp为image/bmp等等。

二、              仅仅输出一张图片二进制流,asp.net 中Page_Load事件先于页面输出被触发,因此图片的输出可以在此事件中进行,直接操作Reponse对象,避免输出与图片无关的而外信息(额外的第二张图片或者文字)。图片的二进制流输出后及时使用Response.End()方法结束http响应,避免页面中的额外信息被asp.net的引擎默认输出到客户端。

 

希望此文能够起到抛砖引玉的作用!^_^

 

附录一:

MainForm.cs

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.IO;

using System.Windows.Forms;

 

namespace InsertImageToDatabase

{

    public class MainForm : System.Windows.Forms.Form

    {

       private System.Windows.Forms.OpenFileDialog openFileDlg;

       private System.Windows.Forms.TextBox filePath;

       private System.Windows.Forms.Button browseButton;

       private System.Windows.Forms.Button insertButton;

       /// <summary>

       /// Required designer variable.

       /// </summary>

       private System.ComponentModel.Container components = null;

 

       public MainForm()

       {

           //

           // Required for Windows Form Designer support

           //

           InitializeComponent();

 

           //

           // TODO: Add any constructor code after InitializeComponent call

           //

       }

 

       /// <summary>

       /// Clean up any resources being used.

       /// </summary>

       protected override void Dispose( bool disposing )

       {

上一页  [1] [2] [3] [4] [5] [6]  下一页

打印本文 打印本文 关闭窗口 关闭窗口