启网、虚拟主机、域名注册、服务器合租
精致合租、5人、10人、15人服务器合租、freebsd合租
当前位置:站长中国 > Asp.net教程 > ASP.NET里面以二进制的形式上传和读取图片

ASP.NET里面以二进制的形式上传和读取图片

2008 - 12 - 16  作者:  来源:  浏览:614  评论: 发布评论 问高手
推荐:启网 - 专业的主机、服务器合租提供商 17hz.net - 5年服务器合租精品服务
    

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    //上传图片

    protected void Button1_Click(object sender, EventArgs e)

    {

        String pathName = this.File1.Value;//获取文件路径

        FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);//创建文件流

        byte[] buffByle = new byte[fs.Length];// 创建一个byte 数组

        fs.Read(buffByle, 0, (int)fs.Length);//读取流 写入缓冲区

        fs.Close();

        // 把二进制存入数据库

        SqlConnection conn = new SqlConnection("server=PC-200807242100;database=phone;uid=sa;pwd=251");

        SqlCommand comm = new SqlCommand();

        conn.Open();

        comm.CommandText = "insert into image values(@image)";

        comm.Connection = conn;

        comm.CommandType = CommandType.Text;

        comm.Parameters.Add("@image", SqlDbType.Image);//必须是Image 内型

        comm.Parameters[0].Value = buffByle;

        int i=comm.ExecuteNonQuery();

        Response.Write(i);

        conn.Close();

    }

    //读取图片

    protected void Button2_Click(object sender, EventArgs e)

    {

        DataTable tb = new DataTable();

        SqlConnection conn = new SqlConnection("server=PC-200807242100;database=phone;uid=sa;pwd=251");

        conn.Open();

        SqlDataAdapter Adapter = new SqlDataAdapter("select * from image ", conn);

        Adapter.Fill(tb);

        byte[] buffByle = (byte[])tb.Rows[0][0];//把数据库中图片的二进制数据转换一个byte数组

        int filelength = buffByle.Length;//获得数组的长度

        //创建在服务器上对应虚拟路径的物理路径

        string myUrl = HttpContext.Current.Server.MapPath(this.Request.ApplicationPath) + @"\TempDownLoad";

        // 创建文件流

        FileStream fs = new FileStream(myUrl, FileMode.OpenOrCreate);

        BinaryWriter w = new BinaryWriter(fs);//以二进制的形式将基元内写入流

        w.BaseStream.Write(buffByle, 0, filelength);//把数据库中的图片二进制添加到BinaryWriter

        w.Flush();

        w.Close();

        Image1.ImageUrl = Context.Request.ApplicationPath + "/TempDownLoad/";

    }

}



推荐教程