|
图片保存在服务器上有两种方式,一种是保存在数据库当中,一种是以为文件的形式保存在网站某个目录下面,不过此目录对web用户具有写的权限,保存在数据库当中是以二进制式的形式保存,是文件流的方式读出来,如果在开发WinForm程序很流这种方法,不过在Web保存在文件夹下面比较好,把文件名保存在数据库当中 下面贴一段以二字制方式保存在数据当中的代码
Code protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { byte[] content =FileUpload1.FileBytes;
SqlConnection Connection = new SqlConnection(@"Data Source=COMPUTERSQLEXPRESS;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=sa"); Connection.Open(); SqlCommand Command = Connection.CreateCommand(); Command.CommandText = "insert into images(image,contentType) values(@image,@contentType)"; Command.CommandType = CommandType.Text;
Command.Parameters.Add("@image", SqlDbType.Image).Value = content; Command.Parameters.Add("@contentType", SqlDbType.NVarChar).Value = GetContentType(new FileInfo(FileUpload1.FileName).Extension.Remove(0, 1));
if (Command.ExecuteNonQuery() == 1) { Response.Write("<script type='text/javascript'>alert('添加成功');</script>"); } } }
private string GetContentType(string extension) { string type="jpeg"; if(extension=="jpg") { type="jpeg"; } else { type=extension; } return "image/"+type; } 这样就以二字形式保存好,下面贴一段读的代码,不过,这段代码只能读取一个值
Code try { SqlConnection connection = new SqlConnection(@"Data Source=COMPUTERSQLEXPRESS;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=sa"); connection.Open();
SqlCommand command = connection.CreateCommand(); command.CommandText = "select * from images id=@id"; //
[1] [2] 下一页 |