图片二进制上传2
上传核心代码:
try
{
string ImgPath = FileUpload1.PostedFile.FileName;
string ImgName = ImgPath.Substring(ImgPath.LastIndexOf("\\") + 1);
string ImgExtend = ImgPath.Substring(ImgPath.LastIndexOf(".") + 1);
if (!(ImgExtend == "bmp" || ImgExtend == "jpg" || ImgExtend == "gif"))
{
Label1.Text = "上传图片的格式不正确!";
return;
}
int FileLen = this.FileUpload1.PostedFile.ContentLength;
Byte[] FileData = new Byte[FileLen];
HttpPostedFile hp = FileUpload1.PostedFile;//创建访问客户端上传文件的对象
Stream sr = hp.InputStream;//创建数据流对象
sr.Read(FileData, 0, FileLen);//将图片数据放到FileData数组对象实例中,其中0代表数组指针的起始位置,FileLen表示要读取流的长度(指针的结素位置)
SqlConnection con = new SqlConnection(connstr);
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO pictures (PicData,PicName,PicType) VALUES (@imgdata,@ImaName,@ImgExtend)", con);
com.Parameters.Add("@imgdata", SqlDbType.Image);
com.Parameters.Add("@ImaName", SqlDbType.VarChar);
com.Parameters.Add("@ImgExtend",SqlDbType.VarChar);
com.Parameters["@imgdata"].Value = FileData;//二进制文本
com.Parameters["@ImaName"].Value = ImgName; //图片名
com.Parameters["@ImgExtend"].Value = ImgExtend;//类型
com.ExecuteNonQuery();
Label1.Text = "保存成功!";
}
catch (Exception error)
{
Label1.Text = "处理失败!原因为:" + error.ToString();
}
图片显示核心代码:
protected void Page_Load(object sender, EventArgs e)
{
string imgid = Request.QueryString["imgid"];
string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["connstr"].ToString();
string sql = "SELECT PicData,PicType FROM pictures WHERE PicId ="
+ imgid;
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
Response.ContentType = dr["PicType"].ToString();
Response.BinaryWrite((byte[])dr["PicData"]);
}
connection.Close();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通