1. 程式人生 > >FileUpload控制元件上傳圖片到資料庫

FileUpload控制元件上傳圖片到資料庫

ASP儲存圖片並顯到網頁例項 

2010-09-15 22:52:32|  分類: .NET |字號 訂閱
using System.IO;
using System.Drawing;

儲存圖片:

前臺:

將 form的enctype屬性改為:

<form id="form1" runat="server" enctype="multipart/form-data">

後臺:

protected void btnsaveiamge_Click(object sender, EventArgs e)

        {

            string getname = TextBox2.Text;

            if (fil1.HasFile)  //判斷是否選種檔案

            {

                string getfile = fil1.PostedFile.FileName;

                string imgtype = fil1.PostedFile.ContentType; //檔案型別

                int i = getfile.LastIndexOf(".");

                string filename;

                filename = getfile.ToLower().Substring(i, getfile.Length - i);

                if (!(filename == ".jpg" || filename == ".jpeg" || filename == ".gif" || filename

== ".png"))

                {

                    ClientScript.RegisterStartupScript(ClientScript.GetType(), "uploaderr",

"<script language='javascript' defer>alert('上傳檔案格式不正確')</script>");

                    return;

                }

                //上傳檔案

                //FileUploadCompant(this.FileUpload1);  

                string strpath = fil1.PostedFile.FileName;  //檔名

                byte[] getimage = new byte[fil1.PostedFile.ContentLength];  //將圖片轉為二進位制檔案 

ContentLength表示上傳檔案的長度

                Stream filestream = fil1.PostedFile.InputStream;

                //讀取資料

                filestream.Read(getimage, 0, fil1.PostedFile.ContentLength);

                strcon = "Data Source=(local); DataBase=NorthWind; UID=sa; PWD=200402025";

                testcon = new SqlConnection(strcon);

                testcon.Open();

                //用引數的方式儲存二進位制圖片到資料庫

                SqlCommand command = new SqlCommand("INSERT INTO ImageStore

(imgtitle,imgtype,imgdata,IMPATH)VALUES ( @imgtitle, @imgtype,@imgdata,@impath)", testcon);

                SqlParameter paretile = new SqlParameter("@imgtitle", SqlDbType.VarChar, 50);

                paretile.Value = getname;

                command.Parameters.Add(paretile);

                SqlParameter paretype = new SqlParameter("@imgtype", SqlDbType.VarChar, 50);

                paretype.Value = imgtype;

                command.Parameters.Add(paretype);

                SqlParameter pareimgdata = new SqlParameter("@imgdata", SqlDbType.Image);

                pareimgdata.Value = getimage;

                command.Parameters.Add(pareimgdata);

                SqlParameter pareimgpath = new SqlParameter("@impath", SqlDbType.VarChar, 200);

                pareimgpath.Value = strpath;

                command.Parameters.Add(pareimgpath);

                int iresult = command.ExecuteNonQuery();

                testcon.Close();

            }

        }

顯示圖片:

新增(*.ashx)檔案

在檔案下編輯

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.IO;

using System.Drawing;

using System.Drawing.Imaging;

using System.Data;

using System.Data.SqlClient;

namespace MiSTest

{

    /// <summary>

    /// LoadImage 的摘要說明

    /// </summary>

    public class LoadImage : IHttpHandler

    {

        private SqlConnection testcon;

        private SqlCommand testcmd;

        string strsql;

        public void ProcessRequest(HttpContext context)

        {

            //context.Response.ContentType = "text/plain";

            //context.Response.Write("Hello World");

            try

            {

                string id = context.Request.QueryString["id"];

                if (!string.IsNullOrEmpty(id))

                {

                      string strcon="Data Source=(local); DataBase=NorthWind; UID=sa;

PWD=200402025";

                      testcon = new SqlConnection(strcon);

                      testcon.Open();

                      testcmd = new SqlCommand();

                      testcmd.Connection = testcon;

                      testcmd.CommandType = CommandType.Text;

                      strsql = "Select * from ImageStore where id="+ id + "";  //根據條件查出對應的

圖片

                      testcmd.CommandText = strsql;

                      SqlDataReader sdr = testcmd.ExecuteReader();

                      if (sdr.Read())

                      {

                          context.Response.ContentType = sdr["IMGTYPE"].ToString();  //獲取圖片型別

                          context.Response.BinaryWrite((byte[])sdr["IMGDATA"]);     //顯示圖片必須

BinaryWrite這種寫入的方式

                      }

                      testcon.Close();

                }

            }

            catch (Exception err)

            {

                context.Response.Write("<script language='javascript' defer='defer'> alert('" +

err.Message + "')</script>");

            }

        }

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

在頁面中顯示圖片

protected void Button3_Click(object sender, EventArgs e)

        {

            Image1.ImageUrl = "LoadImage.ashx?id=" + txtimageid.Text.Trim() +""; //圖片地址指向ashx

檔案並向傳遞數片編號

        }