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

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/";
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值