ASP.NET上传和读取图片文件

一个简单ASP.NET上传读取文件例子

1.前台页面代码:

<body>
    <form id="form1" runat="server">
    <div style="height:1000px">
    <asp:Image ID="Image1" runat="server" />  
    </div>
    <div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">上传</asp:LinkButton>
    </div>
    </form>
</body>

2.后台页面代码:

 protected void Page_Load(object sender, EventArgs e)
    {
        this.ReadImage();
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(this.FileUpload1.PostedFile.FileName))
        {      
        }
    }

    //向数据库插入二进制图片
    private bool AddImage()
    {
        //文件完整路径
        string fileName = this.FileUpload1.PostedFile.FileName;
        //创建文件流
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        //创建byte数字
        Byte[] bytes = new Byte[fs.Length];
        //写入缓冲区
        fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
        fs.Close();
        //写入数据库
        SqlConnection conn = new SqlConnection("Server=(local);User ID=sa;Password=sa;DataBase=Test");
        SqlCommand myCommand = new SqlCommand();
        myCommand.Connection = conn;
        conn.Open();
        myCommand.CommandType = CommandType.Text;
        myCommand.CommandText = "insert into TestImg values(@img)";
        myCommand.Parameters.Add("@img", SqlDbType.Image);//参数类型必须是image类型
        myCommand.Parameters[0].Value = bytes;
        int count = myCommand.ExecuteNonQuery();   
        conn.Close();
        if (count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //从数据库读取二进制图片
    private void ReadImage()
    {
        DataTable dt = new DataTable();
        SqlConnection conn = new SqlConnection("Server=(local);DataBase=Test;User ID=sa;Password=sa");
        conn.Open();
        SqlDataAdapter sa = new SqlDataAdapter("select * from TestImg",conn);
        sa.Fill(dt);
        byte[] bytes =(byte[])dt.Rows[0][1];
        int len = bytes.Length;
        //在服务器上创建对应虚拟路径的物理路径, @"\TempDownLoad"物理文件夹
        string url = HttpContext.Current.Server.MapPath(this.Request.ApplicationPath) + @"\TempDownLoad";
        //穿件文件流
        FileStream fs = new FileStream(url,FileMode.OpenOrCreate);
        //以二进制形式写入流
        BinaryWriter bw = new BinaryWriter(fs);
        //把数据库中的图片二进制添加到BinaryWriter
        bw.BaseStream.Write(bytes,0,len);
        bw.Flush();
        bw.Flush();
        fs.Close();
        this.Image1.ImageUrl = Context.Request.ApplicationPath + "/TempDownLoad/";
    }

3.数据库表代码:

create table TestImg
(
  id int identity(1,1),
  img image
)

原文地址:https://www.cnblogs.com/michaelShao/p/1641418.html