• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

画情画心画影

--寒冬玉
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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/";
    }
}

posted on 2008-12-15 17:17  Winter001  阅读(281)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3